Thursday, October 2, 2008

class << self

I've come across this construct many times while browsing a number of open source projects:
  1. class MyClass  
  2.   class << self  
  3.     def a_class_method  
  4.       ...  
  5.     end  
  6.   end  
  7.   
  8.   def an_instance_method  
  9.     ...  
  10.   end  
  11. 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:
  1. class MyClass  
  2.   def self.a_class_method  
  3.     ...  
  4.   end  
  5.   
  6.   def an_instance_method  
  7.     ...  
  8.   end  
  9. end  

No comments :

Post a Comment