I have a question about how the Ruby interpreter assigns variables:
I use this quite often:
return foo if (foo = bar.some_method)
w
Read it carefully :
Another commonly confusing case is when using a modifier if:
p a if a = 0.zero?
Rather than printing true
you receive a NameError, “undefined local variable or method 'a'”. Since Ruby parses the bare a
left of the if
first and has not yet seen an assignment to a it assumes you wish to call a method. Ruby then sees the assignment to a
and will assume you are referencing a local method
.
The confusion comes from the out-of-order execution of the expression. First the local variable is assigned-to then you attempt to call a nonexistent method.
As you said - None return foo if (foo = bar.some_method)
and return foo if (true && (foo = bar.some_method))
will work, I bet you, it wouldn't work, if you didn't define foo
before this line.
You could do return foo||=nil if foo = bar.some_method
.