这是一个包含一些方法的模块:
module M
def x; y; end
def y; ...; end
end
这是一个类:
class C
def z; ...; end
end
我有两个C
实例:
c1 = C.new
c2 = C.new
我能做些什么来c1
,c1.class
有x
和y
,但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] #=> []