Pregunta

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?

¿Fue útil?

Solución 3

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

Otros consejos

Variable declarations take effect even if the branch where the assignment takes place is never reached.

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
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top