是否将`def self.method_name`和`def method_name`缩短为一个方法?

Kep*_*ond 0 ruby

所以说我有这个课程:

class This
  def a(that)
    puts that
  end

  def self.b(that)
    puts that
  end
end

This.b("Hello!") # => passes
This.a("Hello!") # => fails

the_class = This.new()
the_class.b("Hello!") # => fails
the_class.a("Hello!") # => passes
Run Code Online (Sandbox Code Playgroud)

有没有办法将这两个方法缩短为一个能够在未初始化的对象上调用的方法,并且能够在已经初始化的对象上调用,或者我是否总是必须编写两次这样的方法?

max*_*ner 6

您可以将功能提取到模块中以及它extendinclude它们.

module A
  def a(that)
    puts that
  end
end

class This
  include A # defines instance methods
  extend A # defines class methods
end

This.a("foo") # => "foo"
This.new.a("foo") # => "foo"
Run Code Online (Sandbox Code Playgroud)

虽然我认为这是比较常见的要么include或者extend和不能同时使用.原因是实例方法通常依赖于实例状态,而类方法则不依赖于实例方法.如果你有一个实例This.new并想要调用类方法,你可以使用.classieThis.new.class.a