Why does the last statement (with "if (tmp2 = foo)" at the end of the statement) fail?
def foo;5;end
# this one works
if (tmp = foo)
puts tmp.to_s
end
# why this one fails
puts tmp2.to_s if (tmp2 = foo) #=> undefined local variable or method ‘tmp2’ for main:Object
It fails because of the way the parser works.
From the parser's point of view the variable tmp2 exists from the point in the code at which it is first assigned until the point where it goes out of scope. For this it does not matter, when (or if) the assignment is actually executed, just when the parser sees the assignment (i.e. it depends on the assignments position in the code).
Edit: To expand on that bit:
The decision whether a name is a local variable or a method call is made by the parser. The parser makes that decision solely based on whether or not it has already seen an assignment to that variable. So when the parser sees tmp2 before seeing tmp2 = ...
, it decides that here tmp2 refers to a method. When that part of the code is actually executed, it tries to call the method tmp2 which does not exist so you get the error.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With