As pointed out before, we use the notation of
class << self; def xxx; end; end
is the same as
def self.xxx; end
but use this notation makes that class methods look more consistant with class instance methods, and improve the readbility of your code
I collected some good article from college bbs, save them as html file, they look like this
<html>
<pre>
original post
</pre>
</html>
The following script extract original post from html files, save them as filename.txt
Here I use this ruby library htmltokenizer, ported from Perl http://rubyforge.org/projects/htmltokenizer/
require 'html/htmltokenizer'
collection = Dir['*.html'] # collect inserested html file names in a array...
collection.each do |t| # do our magic in blocks
token = HTMLTokenizer.new(IO.read(t))
token.getTag("pre")
File.open(File::basename(t, ".html") + ".txt", 'w') do |handle| # nested block
so we call the method access_reader(xxx) in the definition of class, and we get the instance method "xxx", we don't use the normal way of
def instance_variable
@instance_variable
end
复制代码
you may think this is just a short notation of making methods, of course it is, however, you may extensively use this technique in your programming practice. The first good practice is define your own version of attr, attr_reader, attr_writer, attr_accessor methods. Why? since then, our class instance can interactive with other objects, that will simplify many things.