Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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
like image 712
Ethan Avatar asked Feb 20 '23 19:02

Ethan


2 Answers

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 :)

like image 76
Sergio Tulentsev Avatar answered Mar 08 '23 14:03

Sergio Tulentsev


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.

like image 24
rfunduk Avatar answered Mar 08 '23 13:03

rfunduk