Top Level Methods
In this chapter, you will learn that the methods defined in the top level context are bound to the main object.
What is Top Level Method?
Top level methods are methods defined in the top level scope. They are not inside a class or module.
Top Level Method
Let's define a method at the top level.
def speak p 'speaking' end
Call Top Level Method
We can call this method like this:
Ruby programs bind methods defined in the top level scope to main as private methods. We can verify this:
Inaccessible in the Self
Ruby programs do not make the top level methods available in the self object.
def speak p 'I am speaking' end p self.public_methods.include?(:speak)
This means, if you call speak method on self:
You will get the error:
NoMethodError: private method ‘speak’ called for main:Object
We will discuss about private methods and how the sender and receiver is the same in the next chapter.
The IRB Convenience
The IRB binds methods in the top level scope to main as public methods for convenience. We can verify it like this:
$irb > def speak > p 'speaking' > end => :speak > speak "speaking" => "speaking" > self.public_methods.include?(:speak) => true
In this chapter, you learned that the methods defined in the top level context are bound to the main object.