tags:

views:

34

answers:

1

I thought in the following, foo should be true

$ irb

ruby-1.9.2-p0 > foo = true if !defined? foo || foo.nil?
 => nil 

ruby-1.9.2-p0 > foo
 => nil 

because foo was at first not defined, but the foo = true part make it temporarily has a nil value, so the !defined didn't catch it, but the foo.nil? should catch it, and make it true... but why is it still nil?

this is related to http://stackoverflow.com/questions/3775402/rubys-foo-true-if-defined-foo-wont-work-as-expected

+3  A: 

Be careful when skipping parenthesis. You meant:

foo = true if !defined?(foo) || foo.nil?

As per your other question, the defined?(foo) will always be true, so really you want to write:

foo = true if foo.nil?
Marc-André Lafortune