Possible Duplicate:
conditional statement and assigning value in ruby
While refactoring some rails code, I have encountered some syntax oddity in ruby.
Given the following method
def get_value
42
end
Why does this work?
if value = get_value
puts value
end
While this does not?
puts value if value = get_value
The latter gives an error: undefined local variable or method `value' for main:Object (NameError). I thought these expressions were equal? When the if-block is evaluated before the puts, value should not be undefined.
It’s due to the parsing of lines, vs execution time. In the first version, value is parsed and set and then the puts evaluated. In the second line, when the parser gets to the variable
puts value, it has not yet been defined. In other words, it can’t run the line to set the variable, until it has first parsed the line.