Thursday, October 2, 2008

class << self

I've come across this construct many times while browsing a number of open source projects:
class MyClass
  class << self
    def a_class_method
      ...
    end
  end

  def an_instance_method
    ...
  end
end
I finally got it today ... there's no black magic ... all "class << self" means is:
add the following class method definitions to the class MyClass.
Or,
open the class MyClass, and add the following class methods.
Now that I'm in the gang and understand this incantation, I'm not sure I like it. It seems like a nice way to group all your class methods together, but if you define several class methods then it becomes harder to recognize whether a method belongs to the class or an instance. I think it's cleaner to explicitly state the ownership of each method:
class MyClass
  def self.a_class_method
    ...
  end

  def an_instance_method
    ...
  end
end

No comments :

Post a Comment