Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can I assign an undefined variable to itself in Ruby and get nil? [duplicate]

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.)

like image 988
Nathan Long Avatar asked Feb 02 '12 22:02

Nathan Long


People also ask

How do you check if a variable is nil in Ruby?

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).

Does Ruby have undefined?

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 does variable mean in Ruby?

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.


2 Answers

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

like image 144
Frederick Cheung Avatar answered Oct 10 '22 22:10

Frederick Cheung


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.

like image 22
theglauber Avatar answered Oct 10 '22 23:10

theglauber