Thus spake [email protected] on 04/21/2007 07:31 PM:
Baz#boo and Baz.new.method(:boo).call dosn’t produce the same result.
Does this surprise anyone?
As far as I understand ruby’s dynamic typing, that output is just
what you would expect:
When you create a new Baz and call it’s boo(), you are actually
holding a class instance to do the dispatching: first the
module-included boo() is run and that looks for a boo() in the
caller’s, i.e. this particular Bar’s, superclass.
In the second case, you create a Baz, but then get hold of the
method itself by a process called “reflection” or “introspection”.
Since everything in ruby is an object, that’s what you get: a method
object representing the method itself.
So, in this case, you are holding the raw boo() method directly from
your Bar module. This method object does not know anything at all
about the instance that provided it, i.e. the new Baz you called
It is just a sniplet of code, wrapped in an object for you.
Now, since Bar itself does not have a superclass, a call to super
in_this_context yields the NoMethodError you encountered.
To cut a long story short, in the first case you call a method on an
instance of Baz and let ruby do all the dispatching for you. In the
second case you grab through the Baz and pull the method directly
from your module and have it execute itself.
The prime thing to remember here is this: if you are using
reflection, always be clear of the context you call a method in, as
this might not always be the same for different approaches.