In `puts "Hello"`, there is no object to the left of a dot, but `puts` is still a method call. Ruby sends it to `self`, the current object. Exactly one object plays that role at any point in execution; which object it is depends on the context. section 1.1.4 section 5.1
Follow the context to find `self`:
- At the top level, `self` is the built-in object that identifies itself as `main`. `main` is not a name you can use to retrieve that object; assign `self` to a variable if you need to keep it. section 5.1.2
- Inside a class or module definition body, `self` is that class or module object. Leaving a nested definition restores the surrounding context. section 5.1.3
- While a method runs, `self` is its receiver. An instance method uses the instance that received the call; a singleton method uses the particular object on which it was defined. For a class method, that object is the class. section 5.1.3
Table 5.1 How the current self object is determined
| Context |
Example |
Which object is self? |
|---|---|---|
| Top level of program |
Any code outside of other blocks |
|
| Class definition |
|
The class object |
| Module definition |
|
The module object |
| Method definitions |
1. Top level (outside any definition block):
|
Whatever object is self when the method is called; top-level methods are available as private methods to all objects |
| 2. Instance-method definition in a class:
|
An instance of |
|
| 3. Instance-method definition in a module:
|
Individual object extended with Instance of class that mixes in |
|
| 4. Singleton method on a specific object:
|
|
Use the context table to check which object receives an implicit method call, especially when moving between definition bodies and method calls. section 5.1.1
A method calls another method
With `class C; def x; puts "x"; end; def y; x; end; end`, calling `C.new.y` runs `x` on that same instance. The call inside `y` needs no dot because its receiver is already `self`. By contrast, at the top of a class definition, a bare call such as `attr_reader :name` goes to the class object. section 5.1.4 section 3.4.1
A bare identifier can also name a local variable. If a local variable and method share a name, the variable wins; `self.talk` or `talk()` makes the method call explicit. Avoiding the clash is simpler. section 5.1.4
Instance variables belong to whichever object is `self` when they are evaluated. Thus `@v` in a class body belongs to the class object, while `@v` in an instance method belongs to the instance that calls it: identical spelling does not make them the same variable. This differs from local-variable scope, which can change without `self` changing. section 5.1.5 section 5.2
