tags:

views:

244

answers:

6

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
  • What's your preferred way to do this?
  • Do you prefer something other than those above?
  • If you use more than one way, under what circumstances do you use them?
+7  A: 

I consistantly 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.

Mr. Matt
A: 

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.

Jason Watkins
A: 

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.

Andrew Grimm
A: 

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.

Yaraher
A: 

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..

science
+1  A: 

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.

Mikoangelo