I’m not really sure why I didn’t just use irb in the first place… sorry.
Anyway, I mostly answered my own question. Just in case anyone else is
wondering:
The first thing to realize is that when you create an instance method, the
associated object would not be a Method, but an UnboundMethod. For example:
irb(main):001:0> class Foo
irb(main):002:1> def foo; ‘foo’; end
irb(main):003:1> end
=> nil
irb(main):004:0> Foo.instance_method(:foo)
=> #<UnboundMethod: Foo#foo>
irb(main):005:0> Foo.instance_method(:foo).id
=> 537250374
irb(main):006:0> Foo.instance_method(:foo).id
=> 537244984
irb(main):007:0> Foo.instance_method(:foo).id
=> 537202282
As you can see, I get back a different object each time, so the (unbound)
method itself is not really an object.
Same is true for bound methods:
irb(main):009:0> x = Foo.new
=> #Foo:0x400911cc
irb(main):010:0> x.method(:foo).id
=> 537158072
irb(main):011:0> x.method(:foo).id
=> 537149042
However, if I were to get an instance of Method or UnboundMethod (I don’t
want to call them “methods”, because they really aren’t methods, they are
objects associated with those methods), and then redefine the method they
associate with, they still refer to the original methods. So it’s almost
like they are real methods. In fact, if calling x.method(:foo).id' returned the same object each time (assuming
foo’ hadn’t been redefined),
they basically would be real methods, wouldn’t they? I mean, methods
would essentially be real objects. I think.
Well, I guess they still wouldn’t show up in ObjectSpace.each_object…
would they? Hmmm… Is there a reason they weren’t made real objects? It
seems like they came awfully close.
But now I have more questions…
First, is there a way to get the Method object for the method being
executed?
Second, why doesn’t this work?
irb(main):001:0> class Foo
irb(main):002:1> def foo; ‘foo’; end
irb(main):003:1> end
=> nil
irb(main):004:0> x = Foo.new
=> #Foo:0x400bc178
irb(main):005:0> def x.foo; ‘bar’; end
=> nil
irb(main):006:0> Foo.instance_method(:foo).bind(x)
TypeError: method foo' overridden from (irb):6:in
bind’
from (irb):6
It works if I don’t define x.foo first.
Chris