你更喜欢在Ruby中定义类方法吗?

Mik*_*use 9 ruby

John Nunemaker最近在博客中介绍了在Ruby中定义类方法各种方法,给出了以下三种选择:

# 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
Run Code Online (Sandbox Code Playgroud)
  • 你最喜欢的方法是什么?
  • 你喜欢上面以外的东西吗?
  • 如果您使用多种方式,在什么情况下使用它们?

Cod*_*eef 12

我一直使用方式1:

class Foo
  def self.bar
    puts 'class method'
  end
end
Run Code Online (Sandbox Code Playgroud)

它并不冗长,它使方法保持在类的相同上下文中.