Mike Woodhouse Mike Woodhouse - 1 year ago 33
Ruby Question

How do you prefer to define class methods in Ruby?

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?


Answer

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.