问题
This is something strange I've figured out in ruby 1.9.3.
Here is the code:
>> r = true
>> if r
>> a = "hello"
>> else
>> b = "hello"
>> end
Now the value of a
is "hello":
>> a
=> "hello"
And strangely the value of b
is nil
>> b
=> nil
Since b
is nowhere in the scene, it should be undeclared.
Why?
回答1:
The local variable is created when the parser encounters the assignment, not when the assignment occurs:
=> foo
# NameError: undefined local variable or method `foo' for main:Object
=> if false
=> foo = "bar" # does not assign to foo
=> end
=> nil
=> foo
=> nil
回答2:
Variable declarations take effect even if the branch where the assignment takes place is never reached.
回答3:
The reason for this is explained in the Ruby documentation, and it is valid for any version of Ruby, not just 1.9:
The local variable is created when the parser encounters the assignment, not when the assignment occurs.
This means that if the parser sees an assignment in the code it creates the local variable even if the assignment will never really occur. In this case the value referenced by the variable is nil
:
if true
a = 0
else
b = 0
end
p local_variables
# => [:a, :b]
p a
# => 0
p b
# => nil
来源:https://stackoverflow.com/questions/21180760/variable-in-else-condition-assumed-nil-value