liveBook · Manning

Top-level method

As explained in The Well-Grounded Rubyist, Fourth Edition

A top-level method is a Ruby method available from the top-level execution context, typically through private methods supplied by Kernel.

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

How The Well-Grounded Rubyist, Fourth Edition covers it

How deep it goes
Explains definition, lookup, privacy, and Kernel origins, but stops short of broader metaprogramming treatment.
Examples
Uses talk, puts, print, Kernel method inspection, and an Object receiver to contrast permitted and rejected calls.
What it assumes
Assumes basic Ruby methods and objects while establishing top-level self, Object lookup, and private visibility.
What you can do after
Apply it by writing script-level commands and diagnosing receiver errors through Ruby’s private-method rules.
How it connects
Connects top-level methods to self, scope, method visibility, Object, Kernel, and private methods.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Well-Grounded Rubyist, Fourth Edition. The section links point to the parts of the book it draws on.