After finishing the chapter “The Object Model” in Metaprogramming Ruby, I got confused.
Is an object(instance of some class)’s method the same as the instance methods of its class in Ruby?
It sounds true. because we know the object’s methods stored in its class.
class W;end
W.methods == Class.instance_methods # => true
# Also
String.instance_methods == "abc".methods # => true
W is an instance of Class. but if I reopen W and define a new method for it, than make confuse.
class W
def self.foo
"bar"
end
end
W.methods == Class.instance_methods # => false
W is a instance of Class, and W‘s methods is Class‘s instance method. but if :foo didn’t get stored in Class, than where is it stored?
The method
wtfis stored inside theWclass, not in Ruby’sClassclass.Think of it as inheritance, when you define a method in the inheriting class it is not available in the inherited class. Likewise, when you define a method in the
Wclass it is not available in theClassclass.You do not affect the inherited class when you add a method in the inheriting class.
Although I do not recommend messing with Ruby’s internal Class class, you can add methods to it by monkey patching it:
Now
Class.methods.grep /wtf/will return you the added method.