Global methods in Ruby

ruby

Solution

For runtime Ruby has special object the `main`.

It's some kind of trick that all code runs in the context of this object.

So when you're typing methods like `puts`, `p` and so on, all of them are calling in the context of `self` object and passing to `self` object.

And here's the second thing - the access control. As you probably know, Ruby has keywords like `private`, `protected` and `public` - all of them manage the access of calling methods on object. Ruby is checking this access control only when you're have construction like

`<name_of_object>.your_method` and `self.your_method`

So when you're typing

self.p "something"

Ruby will decline this call because the `p` method is private method.

Problem

If all 'functions' in Ruby are methods, so when I call methods without explicitly mentioning the object they are invoked on, who are they sent to? The Ruby Programming Language book (Flanagan & Matsumoto) says if the object is omitted the method is invoked on self. So if this code works ``` p "123" ``` Then this should work ``` self.p "123" ``` but it doesnt! In this case I ran this in global scope so self is main and self.class is Object. So I can't invoke p on a simple Object instance (which makes sense). I understand that Object includes Kernel where p is declared. How does the interpreter know how to access this declaration?

Original source

Related problems