Variable in else condition assumed nil value [duplicate]

陌路散爱 提交于 2019-12-08 05:49:00

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!