Ruby Language There is always an implicit receiver


In Ruby, there is always an implicit receiver for all method calls. The language keeps a reference to the current implicit receiver stored in the variable self. Certain language keywords like class and module will change what self points to. Understanding these behaviors is very helpful in mastering the language.

For example, when you first open irb

irb(main):001:0> self
=> main

In this case the main object is the implicit receiver (see for more about main).

You can define methods on the implicit receiver using the def keyword. For example:

irb(main):001:0> def foo(arg)
irb(main):002:1> arg.to_s
irb(main):003:1> end
=> :foo
irb(main):004:0> foo 1
=> "1"

This has defined the method foo on the instance of main object running in your repl.

Note that local variables are looked up before method names, so that if you define a local variable with the same name, its reference will supersede the method reference. Continuing from the previous example:

irb(main):005:0> defined? foo
=> "method"
irb(main):006:0> foo = 1
=> 1
irb(main):007:0> defined? foo
=> "local-variable"
irb(main):008:0> foo
=> 1
irb(main):009:0> method :foo
=> #<Method: Object#foo>

The method method can still find the foo method because it doesn't check for local variables, while the normal reference foo does.