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 Methods

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:

speak

This prints:

speaking

Private Method

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

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

Sending a Message to Private Method

We will discuss about private methods and how the sender and receiver is the same in the next chapter.

Talking to Yourself

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

Summary

In this chapter, you learned that the methods defined in the top level context are bound to the main object.

results matching ""

    No results matching ""