Created
December 7, 2012 14:41
-
-
Save latentflip/4233671 to your computer and use it in GitHub Desktop.
Ruby Pop Quiz
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Foo < BasicObject | |
def method_missing(method, *args, &block) | |
puts "You called #{method}" | |
end | |
end | |
Foo.new.hi |
The way to avoid this is to use the global $stdout.puts
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the record, this will raise a stack overflow error, eventually.
Why? 2 reasons.
This means that if a message is not a keyword, or a global, it will be sent to
self
.Here are ruby's keywords:
Note the suspicious lack of
puts
. This means that when we useputs
we are not calling a ruby keyword, but we are sending a messageputs
to the implicit receiver (self.puts
).So where does puts come from?
Kernel
: http://ruby-doc.org/core-1.9.3/Kernel.html#method-i-putsFortunately
Kernel
is mixed intoObject
(http://ruby-doc.org/core-1.9.3/Object.html), which means it's available to any object in our system which inherits fromObject
, which is mostly all of them. So we can normally useputs
without thinking about it.But here we don't inherit from
Object
, we inherit fromBasicObject
, which is a ruby 1.9 addition, which gives us a very empty class, with only the bare minimum of methods:So there is no
puts
on our object. So callingputs
on our object will callmethod_missing
which callsputs
and so on, until ruby gives up.Fun huh?