A Little irb Context
Fri Apr 11 08:00:00 UTC 2008
When you’re sitting at your irb prompt, sometimes it can get a little confusing trying to remember the context in which all those commands you’re entering are executed. We know that anything entered at the prompt in irb is executed in some context, but it’s easy to forget what it is since it’s loaded for you and is not explicit.
We know that if we ask irb about itself, it tells us its class is Object
>> self.class
=> Object
So if we take that together with two facts from the pickaxe book:
"class and module definitions are executable code", and "a class definition is executed with that class as the current object"
we can begin to cobble together an answer. Great! What was the question again?
The question: what is the context of that irb prompt?
The answer: you are entering code into the class definition of the Object class, and it is being executed in the context of an instance of the Class for Object named ‘main’. Clear? I thought so.
class Object
# all of Object's methods defined here
# Now imagine that your irb prompt is sitting right here,
# in this gap in Object's class, right before the final end,
# flashing at you, waiting for you to do great things.
# >>
# And every time you hit the Return key, the entire class
# definition for Object is executed again, with whatever
# command(s) you entered at the prompt appended to the
# end of the class definition.
end
This means you can do things like
class Object
# all of Object's methods defined here
# >>
private
def foo(arg)
puts "#{arg}"
end
foo("bar")
# And you'll see "bar" output.
# Now define a class to play around with
class Fool
def touch
"slap!"
end
end
fool = Fool.new
puts fool.touch
# And you'll see "slap!"
end
Obviously this is a gross over-simplification of what irb is. But maybe this little Gedankenexperiment will help contextualize your irb-ing.