Possible Duplicate:
Why is `a = a` `nil` in Ruby?
I'm sure there is a reason for this behavior i'm just curious what it is.
y = x # NameError: undefined local variable or method 'x'
x = x # => nil
This is caused by the way variables are initialized in Ruby, which is rather unique to this language. Basically, Ruby initializes (creates) a variable if it could possibly get assigned a value. Consider this example:
if false
x = "hello"
end
x
will definitely not get assigned the "hello"
string here. However, it will still get initialized with nil
as from the static program analysis, it could have been assigned.
Your example is similar. Because you assign something to x
, it will get initialized with nil
before the statement is executed. Thus, during execution, x
is in fact nil
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With