类方法可以添加到 Ruby 对象的某些实例中,但不能添加到其他实例中



这是一个包含一些方法的模块:

module M
  def x; y; end
  def y; ...; end
end

这是一个类:

class C
  def z; ...; end
end

我有两个C实例:

 c1 = C.new
 c2 = C.new

我能做些什么来c1c1.classxy,但c2.class没有?我没有看到颠覆方法查找的直接方法。

与其做c1.class.x,为什么不做c1.x,正如得墨忒耳定律所建议的那样?

class C
  def self.x
    "hi"
  end
end
c1 = C.new
c2 = C.new
def c1.x
  self.class.x
end
c1.x # => "hi"
c2.x # NoMethodError

你可以覆盖c1.class以返回C以外的内容(另一个东西会扩展M)。除此之外,没有。

请注意,覆盖c1.class几乎肯定是一个坏主意。一个对象不应该谎报它的类是什么。

也许这个

c1.extend(M)
c1.methods & [:x, :y] #=> [:x, :y]
c2.methods & [:x, :y] #=> []

最新更新