Reputation: 52316
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
Upvotes: 9
Views: 664
Reputation: 43996
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.
Upvotes: 12
Reputation: 93
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.
Upvotes: 3
Reputation: 86
I use Way #3, but I think Way #1 is great also. It depends on your usage. If you want your code to be "cut/pastable" into other modules and classes, then Way #1 is better. I use Way #3 to actually make it more of pain to cut/paste code, b/c Ruby's mantra is "don't repeat yourself" so you shouldn't cut/paste code very often..
Upvotes: 0
Reputation: 2640
Agree with most of the users. I tend to use primarily the
# Way 1
class Foo
def self.bar
puts 'class method'
end
end
There are some small differences, if I recall correctly, that are shown on the Pragmatic Programmers Metaprogramming talks (which I recommend), which relate to how the class code is called and executed.
They were quite small, though and mostly things we won't have to deal with on a normal basis. Will see if I can check them out and post it.
Upvotes: 1
Reputation: 81480
I view << for adding a method as too unusual (though I happily use << with strings and IO).
I avoid Foo.bar because it means repeating yourself.
Upvotes: 0
Reputation: 2692
I prefer Way 1 as it isn't context sensitive. I dislike jumping into the middle of a file and then having to scroll up or down to see if the indentation means I'm in a class << self
block or if it's just a nested module.
Upvotes: 1