Ruby Language Reference

Top Level Methods

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. Let's define a method at the top level.

def speak
  p 'speaking'
end

We can call this method like this:

speak

This prints:

speaking

Ruby programs bind methods defined in the top level scope to main as private methods. We can verify this:

p self.private_methods.include?(:speak)

This prints:

true

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 prints:

false

This means, if you call speak method on self:

self.speak

You will get the error:

NoMethodError: private method ‘speak’ called for main:Object

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

Summary

We saw that the methods defined in the top level context are bound to the main object.

Essential Ruby Book

This concept is explained with diagrams in the Essential Ruby Kindle book.


Sharing is Caring