Jeffrey Yong Jeffrey Yong - 1 month ago 6
Ruby Question

Different Ways of Creating Class Method in Ruby

Example 1:

class Dog
def self.class_method
:another_way_to_write_class_methods
end
end

def test_you_can_use_self_instead_of_an_explicit_reference_to_dog
assert_equal :another_way_to_write_class_methods, Dog.class_method
end


Example 2:

class Dog
class << self
def another_class_method
:still_another_way
end
end
end

def test_heres_still_another_way_to_write_class_methods
assert_equal :still_another_way, Dog.another_class_method
end


May I know which way of writing the class method is preferred in Ruby and why? Are there situations where one is preferred over another?

Answer

this ruby style guide says the class << self syntax is "possible and convenient when you have to define many class methods."

They have code examples using both versions, so there's definitely not a broad community consensus for using one over the other.

I personally use def self.my_method to minimize indentation

Comments