Wednesday, June 20, 2007

Inside a class method "self" points to the class!

I often find this kind of construct in Ruby source files (Ruby's stdlib included):

class Parser

  # ...

  def Parser.parse_file(filename)
    parser = Parser.new(File.open(filename, 'rb'))
    parser.parse
  end

end

However, when you are inside a class method, the self variable already points to the class of the method. Thus, prepending the call to new with the class' name is unnecessary repetition. Moreover, although either self or the class name is still required before the name of a class method definition, I find the former form a better option. In the event of a refactoring involving a change in the class name, you'd be less prone to mistakes.

So, the code above could have been written as:

class Parser

  # ...

  def self.parse_file(filename)
    parser = new(File.open(filename, 'rb'))
    parser.parse
  end
  
end

There's a small caveat regarding inheritance, though. In the first construct, parse_file will always create an instance of Parser, while the second will create an instance of the class specified in the call to parse_file. That might be desirable or not.

0 comments: