Can class methods be added to some instances of Ruby objects but not others?
-
01-06-2021 - |
Question
Here is a module containing some methods:
module M
def x; y; end
def y; ...; end
end
Here's a class:
class C
def z; ...; end
end
I have two instances of C
:
c1 = C.new
c2 = C.new
Is there something I can do to c1
such that c1.class
has x
and y
, but c2.class
doesn't? I don't see a straightforward way to subvert the method lookup.
La solution
You could override c1.class
to return something other than C (and that other thing would extend M). Other than that, no.
Note that overriding c1.class
is almost certainly a bad idea. An object shouldn't lie about what its class is.
Autres conseils
Rather than doing c1.class.x
, why not do c1.x
, as the Law Of Demeter would suggest?
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
Maybe this
c1.extend(M)
c1.methods & [:x, :y] #=> [:x, :y]
c2.methods & [:x, :y] #=> []
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow