A few days ago, a curious question was asked on /r/ruby, which can be boiled down to this: How are the methods of the Kernel module available in the t

There is no such thing as a global method (in Ruby)

submited by
Style Pass
2024-10-21 11:00:05

A few days ago, a curious question was asked on /r/ruby, which can be boiled down to this: How are the methods of the Kernel module available in the top-level scope?

The question was dedicated to rand method, but (as the author correctly suggests) it also applies to many seemingly “top-level” methods documented as belonging to the Kernel module, even as base as puts (print a string), require (load code from another file), or raise (an exception).

We know that in Ruby, all methods belong to some objects and are defined in their classes or modules. The documentation suggests that all of those “global” methods are coming from the Kernel module, yet you typically call them without referring to any module, object, or any other ceremonies (like loading some namespace or adding it to the current scope). So, how to understand this working?

In Ruby (unlike most other OO languages), the bare lowercase identifier foo always refers to either a local variable or (if there is no such variable in the current scope) the method of the current object (the one that self refers to in the current scope).

Leave a Comment