John Nunemaker recently blogged about the various ways to define class methods in Ruby, giving these three alternatives:
# Way 1
class Foo
def self.bar
puts 'class method'
end
end
# Way 2
class Foo
class << self
def bar
puts 'class method'
end
end
end
# Way 3
class Foo; end
def Foo.bar
puts 'class method'
end
I consistently use Way 1:
class Foo
def self.bar
puts 'class method'
end
end
It's not verbose, and it keeps the method in the same context of the class.
I generally prefer def self.foo
for single methods, and class << self
for long stretches of class methods. I feel it makes the distinction between the class method part and the instance method part of the class definition.
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