Many times in this book we've claimed that everything in Ruby is an
object. However, there's one thing that we've used time and time again
that appears to contradict this---the top-level Ruby execution environment.
Not an object in sight. We may as well be writing some variant of
Fortran or QW-Basic. But dig deeper, and you'll come across objects
and classes lurking in even the simplest code.
We know that the literal
"Hello, World"
generates a Ruby
String
, so there's one object. We also know that the bare method
call to
puts
is effectively the same as
self.puts
. But
what is ``self''?
At the top level, we're executing code in the context of some
predefined object. When we define methods, we're actually creating
(private) singleton methods for this object. Instance variables belong
to this object. And because we're in the context of
Object
, we can
use all of
Object
's methods (including those mixed-in from
Kernel
)
in function form. This explains why we can call
Kernel
methods
such as
puts
at the top level (and indeed throughout Ruby):
these methods are part of every object.