Monday, April 16, 2012

Why do we use the "class << self" expression?

In Ruby there are several ways to declare a class method.



We have these two forms...



class Dog

def self.species
puts "I'm a dog."
end

def Dog.species_rly?
puts "Still a dog."
end

end


And this other, longer form...



class Dog
class << self
def species_srsly?
puts "OK, fine. I'm a cat."
end
end
end


Why is the last form used? How is it better than just doing this?



class Dog
def Dog.some_method
# ...
end
end




No comments:

Post a Comment