programmer321 programmer321 - 1 month ago 6
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
end

def callmethod
words = method
result = printout(words)
end

def printout(words)
puts (words)
end

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


How does Ruby recognize that the variable
words
is part of the method call (
callmethod
) when it has not been called explicitly? In this case, the line I am specifically talking about result =
printout(words)
. 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?

Answer

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.

Comments