Top-level Object
Learn about the top-level object in Ruby.
We'll cover the following
We’ve learned that objects come with lots of methods attached to them. We’ve seen how we can use them to do interesting things with the object by way of calling these methods.
Now, try running the following code:
puts is_a?(Object)#trueputs methods#[:to_s, :inspect, ... ]
Note: We can use some methods in Ruby without even defining an object at all. They’re already there. The
is_a?
method tells us that this already is an object, whatever this is.
This is a rather remarkable concept, so we’ll explore it in depth.
What is the top-level object?
Whenever we open IRB (an interactive Ruby environment, more on this later) and it presents a prompt to us, or when we create a new, empty Ruby file, Ruby doesn’t merely execute our code. Before it does, it first creates an empty anonymous Object and places us inside of it.
This empty Object
is invisible in a sense, and it seems that those methods that we can define in this scope (space) were somehow standing alone. In fact, they aren’t. They’re defined on this empty anonymous Object
that we usually don’t see.
This Object
is often referred to as the top-level scope in Ruby.
The top-level scope is an empty anonymous object. All Ruby code starts here.
It can be confusing, but it comes naturally to many Ruby programmers eventually.