Top-level scope is the context of Ruby code written outside any class- or module-definition block. Before entering such a block, or after leaving one, Ruby uses a startup self object called main. section 5.1.1 section 5.1.2
Top-level code establishes several behaviors:
- Assignments create local variables in the top-level local scope. section 5.1.2 section 5.2.2
- A method defined outside a class or module is a top-level method; Ruby makes it available as a private method through Kernel and Object. section 5.1.2 section 5.5
- Crossing into a class, module, or method definition creates a new local scope, so similarly named local variables can remain independent. section 5.2.2
Inspecting the top-level self
At the top level, `ruby -e 'puts self'` identifies the current object as `main`. Ruby does not let `main` serve directly as a reference name; assign `self` if you need to retain that object: `m = self`. section 5.1.2
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:
|
|
Compare top-level self with self inside class, module, instance-method, and singleton-method contexts. section 5.1.1
class C
a = 1 1
def local_a
a = 2 2
puts a
end
puts a 3
end
c = C.new
c.local_a 4
Trace how local scope changes between top-level code, a class definition, and an instance method. section 5.2.2
