Borrowing from cdcarter:
>> def method_missing s; s end
Now we can write like the English Romantics:
>> for desires in heaven do not always end or fade
=> :each
What’s the shortest way to get irb
to respond as follows?
=> some lovers remain unhappy even in paradise
I’m afraid that it’s not going to be very short. Maybe there’s a better closing line? Bonus if you keep up the rough anapests.
What…is going on here.
The descent of the muse, probably?
That sure is slick. I love how
:each
comes tumbling out of thefor
/in
syntax.Seems like we need a new word to describe sentences that parse as valid Ruby with this trick.
Guess that answers the question.
Klondike: http://errtheblog.com/post/31
Chris, Klondike: actually, it turns out that the
for
/in
block parameter doesn’t get its own lexical scope at all:This is the opposite of
obj.each {|| }
behavior, even thougheach
is still called. Word on the street is that it’s a special case in MRI.Wow, I love your auto-reformat-comments plugin. Can I get some?
The way I understood it, we’ve got this basic structure:
To run that code, the Ruby interpreter is going to call the
each
method on{bar}
and pass it the block.In the case above,
{bar}
is the word heaven. The interpreter is going to try and call a method namedheaven
on Kernel (or Object? I forget) and not find one, invoking our newmethod_missing
, which will return the symbol:heaven
.It then tries to call
each
on the symbol:heaven
. Since the Symbol class does not define aneach
method,method_missing
is again invoked, returning the symbol:each
.The block is effectively ignored—our
method_missing
does not care about it—and you get:each
. Because we have a true value, the conditional is short-circuited, and we receive the symbol as our final result.Does that sound about right?
Chronic: right. The missing methods are sent to the
irb
context (main
), but our handler gets defined on Object because of the wayirb
works (this way Symbol gets it too). And regularEnumerable#each
returnsself
, but ourmethod_missing(:each)
returns the first param.Nick: it’s not auto. Just keeping the discourse level high. :)
Right, cool.
So I guess this is the answer to your first question…
Note that Rubinius supports all this literature already: