From: Brian Candler Date: 2007-04-05T14:33:57+09:00 Subject: Re: nil? and non-existent objects On Thu, Apr 05, 2007 at 06:56:46AM +0900, Jamal Soueidan wrote: > 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??? > > > > Someone mentioned that = has higher precedence than if, so it could be > > that in the first statement x is assigned 1 before the conditional > > statement is run. However, x.nil? would then always return false. > > You could also fix it this way :) > > ---------------------------------------------- > > def x > @x > end > > def x=(val) > @x = val > end > > puts x=1 if x.nil? > > ---------------------------------------------- > > This would output: 1 I think you should check your work before posting (I do) Run this: def x puts "calling main.x" @x end def x=(val) puts "calling main.x=" @x = val end puts x=1 if x.nil? You'll see that your two methods are never called, so they don't make any difference.