Question

I have a question about how the Ruby interpreter assigns variables:

I use this quite often:

return foo if (foo = bar.some_method)

where some_method returns an object or nil.

However, when I try this:

return foo if (true && (foo = bar.some_method))

I get: NameError: undefined local variable or method foo for main:Object.

What is the difference in evaluation between the first and second lines that causes the second line to error?

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top