Search code examples
rubyprogram-entry-point

Calling a method without an explicit receiver in the main environment


When I do:

def hello(*args)
  "Hello " + args.join(' ')
end

send( :hello, "gentle", "readers")  #=> "Hello gentle readers"

is send called on something? I get:

method(:hello).owner #=> Object

Is it called on the Object class or its instance?


Solution

  • Method call without explicit receiver:

    send( :hello, "gentle", "readers")
    

    assumes an implicit self as the receiver, which is the main object in this case.

    Method definition in the main environment:

    def hello(*args)
      "Hello " + args.join(' ')
    end
    

    assumes it is defined as an instance method on Object.

    Since main is an instance of the Object class, the method definition and the call work together.