0

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?

sawa
  • 165,429
  • 45
  • 277
  • 381

2 Answers2

0

Your method:

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

is the same as:

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

where self in this case is defined as main which is the built-in top-level object.


This line of code:

p method(:hello).owner #=> Object

returns Object because you've defined the method :hello at the top-level which means it gets put into the class Object.

Sagar Pandya
  • 9,323
  • 2
  • 24
  • 35
  • Thank you. Your reference to main helped me find additional details. –  Feb 28 '16 at 01:41
0

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
  • 1
    I found this post, which says: Ruby allows you to define simple functions at the top level scope. How does Ruby do this? Before your script starts to run, Ruby automatically creates a hidden object known as the top self object, an instance of the Object class. This object serves as the default receiver for top level methods. The string “main” is how Ruby represents the top self object as a string. http://www.sitepoint.com/rubys-top-self-object/ –  Feb 28 '16 at 01:40