Why can I assign an undefined variable to myself in Ruby and get null?

Possible duplicate:
Why a = a nil in Ruby?

There, say, a “strange phenomenon” in Ruby using undefined variables. This is something 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 myself in Ruby and get itnil ?

Notice that I'm using Ruby 1.9.3 here. I'm not sure other versions may be true.

(Thanks to Gary Bernhardt for demonstrating this in his hilarious conversations .)

+5
source share
2 answers

The fact that bar undefined is actually not the most interesting part, since the appointment does not even need to be tried, for example

if false
  foo = 1
end

foo nil. , scope , , . Ruby , , nil. . http://ruby.runpaint.org/variables#local

+7

- Ruby, - , . singleton nil, .

foo = bar

"foo" . , Ruby "", foo ( ? ?), , .

+2

All Articles