سؤال

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?

هل كانت مفيدة؟

المحلول 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

نصائح أخرى

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
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top