Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you prefer to define class methods in Ruby?

Tags:

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?
like image 290
Mike Woodhouse Avatar asked May 19 '09 09:05

Mike Woodhouse


2 Answers

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.

like image 113
Codebeef Avatar answered Sep 21 '22 16:09

Codebeef


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.

like image 24
Mikoangelo Avatar answered Sep 17 '22 16:09

Mikoangelo