A top-level method is defined outside any class or module, in the context of Ruby’s automatically created top-level object, self = main. Ruby stores a user-defined top-level method as a private instance method of Object, making it convenient for short scripts while preserving ordinary method and visibility rules. section 5.4 section 5.1.2
Use top-level methods according to these rules:
- Call a private top-level method bare, such as talk, or explicitly on self; calling it on another receiver raises an error. section 5.4.1
- Recognize that Object lies in the method-lookup path of ordinary objects, so a top-level method can be resolved from different self values. section 5.4.1
- Distinguish user-defined top-level methods from built-in top-level methods: puts, print, require, load, and raise are private instance methods supplied by Kernel. section 5.4.2
A script-friendly command
def talk puts "Hello" end talk self.talk obj = Object.new obj.talk # fails: talk is private The definition behaves like a private method added to Object. The bare call and self.talk use the permitted receiver; obj.talk uses an explicit receiver other than self. section 5.4.1
$ ruby -e 'p Kernel.private_instance_methods.sort'
Inspect Kernel’s private instance methods to discover the built-in commands available without explicit receivers. section 5.4.2
