alavni shubham
alavni shubham

Reputation: 99

The following program prints the value of the variable. Why?

hello_world = 'Hello Ruby World' 

def hello_world
  'Hello World' 
end

puts hello_world

Please explain why prints variable's value?

Upvotes: 0

Views: 48

Answers (1)

kiddorails
kiddorails

Reputation: 13014

In case of ambiguity when compiler finds a variable and method with same name in same scope, it gives precedence to the variable.

To call the method explicitly, send empty parens ()

hello_world = 'Hello Ruby World' 

def hello_world
  'Hello World' 
end

puts hello_world()

or provider an explicit receiver to the method, in this case, using self

self.hello_world

Edit: As sepp2k advised in comments below, self.hello_world would not work with a ruby(.rb) file. Just to try, you can dynamically dispatch the method with send:

send(:hello_world) #or
method(:hello_world).call

Upvotes: 4

Related Questions