Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does conditional statement and assigning value in ruby fails if the "if" statement is at end of clause?

Tags:

ruby

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
like image 310
Neeraj Singh Avatar asked Sep 04 '09 16:09

Neeraj Singh


1 Answers

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.

like image 97
sepp2k Avatar answered Oct 20 '22 07:10

sepp2k