programmer321 programmer321 - 8 months ago 61
Ruby Question

In Ruby, how do variables get passed into arguments without a method call?

Given the following code:

def method
words = "33"
return words

def callmethod
words = method
result = printout(words)

def printout(words)
puts (words)

callmethod #will print out --> "33" (words from method)

How does Ruby recognize that the variable
is part of the method call (
) when it has not been called explicitly? In this case, the line I am specifically talking about result =
. It seems that this function is picking up the variable words (return value of method), even though I haven't used the method call to explicitly put it in. Can someone explain to me how this is possible?


Within callmethod method words is a local variable with the value of return value of method method.

printout(words) works as expected, because you are passing it a value of local variable words, which is string "33".

In Ruby method_name() are optional while calling a method. If you happen to have a local variable with the same name, as a method, to make Ruby know you want to call a method, not to get a value of local variable, you can say method_name(). But there is a better/recommended option - self.method_name.