Possible Duplicate:
Why a = a is nil in Ruby?
There's a, shall we say, "odd phenomenon" in Ruby with using undefined variables. It's like this:
# irb session follows
#
foo # undefined local variable or method 'foo'
bar # same for 'bar'
foo = bar # still same for 'bar'
foo = foo # nil - HUH?
foo # is now set to nil!?
Why can I assign an undefined variable to itself in Ruby and get nil
?
Note that I'm using Ruby 1.9.3 here. I'm not sure what other versions this may be true in.
(Thanks to Gary Bernhardt for demonstrating this in his hilarious talk.)
In Ruby, you can check if an object is nil, just by calling the nil? on the object... even if the object is nil. That's quite logical if you think about it :) Side note : in Ruby, by convention, every method that ends with a question mark is designed to return a boolean (true or false).
Undefined instance variables are always nil , so you want to check for that. Try the “safe navigator operator” (Ruby 2.3+) which only calls a method if the variable is not nil .
What is a variable? A variable is a name that Ruby associates with a particular object. For example: city = "Toronto" Here Ruby associates the string "Toronto" with the name (variable) city. Think of it as Ruby making two tables.
The fact that bar is undefined is actually not the most interesting part, since the assignment does not even need to be attempted, for example
if false
foo = 1
end
Sets foo to nil. As i understand it, local variable scope is determined statically in that it is determined without actually running the code, merely by analysing it. Ruby thinks the assignment could happen so it creates the local variable and sets it to nil. See http://ruby.runpaint.org/variables#local
Nil is magic in Ruby, because of the idea that everything is an object. There is actually a singleton nil object that gets assigned. When you did
foo = bar
the "foo" variable sprang into existence and took as value the magic nil object. Before you did the assignment, Ruby didn't have a way of "knowing" what foo is (is it a variable? a method call?), but once you do the assignment, it starts treating it as a variable.
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