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
This wonderful book says that the three syntaxes are identical. Which one to choose is a matter of personal preference. It also says that class name syntax (def Dog.some_method
) is frowned upon by Ruby community. And I can see why: you're duplicating information without a reason. Should you rename your class, you'll have to update all method definitions as well.
So, you're free to choose between the remaining two syntaxes :)
You'll find that the class << self
form is only longer when you're dealing with a small number of methods. If you are going to write, say, 15 class methods, suddenly it's a lot clearer and a lot less repetitive.
At the end of the day it's a matter or personal style which you use.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With