From: Phrogz Date: 2007-04-05T04:55:13+09:00 Subject: Re: nil? and non-existent objects On Apr 4, 1:25 pm, "Fran�ois Montel" wrote: > Why is it that the nil? method can sometimes be called on an object that > doesn't exist, and other times will return an error. Under what > circumstances can you call the nil? method on a non-existent object? > > Consider: > > >> puts x = 1 if x.nil? > => 1 > >> puts 'z is not defined' if z.nil? > > => NameError: undefined local variable or method 'z' Consider this: irb(main):001:0> puts x=1 if x => nil irb(main):002:0> puts y if y=1 (irb):2: warning: found = in conditional, should be == NameError: undefined local variable or method `y' for main:Object irb(main):003:0> if z=1 then puts z end (irb):3: warning: found = in conditional, should be == 1 => nil The difference between them is the order in which Ruby sees the assignment *when preparing* (syntax parsing), not during execution. The 'y' and 'z' cases above should run the same way, but due to the way Ruby checks to determine if a variable exists, it needs to see an assignment earlier in the file than a reference to the value.