From: Robert Klemme Date: 2011-01-26T17:15:04+09:00 Subject: Re: The finer points of postfix conditionals. On Tue, Jan 25, 2011 at 11:53 PM, Peter Vandenabeele wrote: > Robert Klemme wrote in post #977145: >> On Mon, Jan 24, 2011 at 3:22 PM, Jon Leighton >> wrote: > ... >>> and even: >>> >>> if false >>> foo = 1 >>> bar = 2 >>> end >>> >>> (results in both foo and bar being assigned nil) >> >> This is not exactly true: foo is not "assigned nil" but rather is foo >> initialized as a local variable and initially a variable refers nil. >> There is no assignment but because you have an assignment in code >> (even though it's no executed) the local variable comes into existence >> (see above). > > To understand this better, I used the method 'defined?'. > Would 'defined?' be a correct way to determine if a name was > already 'initialized as a local variable' in this case? You can certainly do that for learning purposes but I have not yet had the need to use defined? in a real program. > $ rvm use 1.9.2  # (same behavior in 1.8.7) > Using /home/peterv/.rvm/gems/ruby-1.9.2-p136 > $ irb > 001:0> defined?(x)  #=> nil > 002:0> if false > 003:1> x = 10 > 004:1> end  #=> nil > 005:0> defined?(x)  #=> "local-variable" > 006:0> x  #=> nil IRB cannot be trusted on things like this as it has different behavior for local variables than the Ruby interpreter. Better do something like this: 09:10:10 ~$ ruby19 < def f > p defined?(x) > if false > x=10 > end > p defined?(x) > end > f > CODE nil "local-variable" 09:11:06 ~$ Kind regards robert -- remember.guy do |as, often| as.you_can - without end http://blog.rubybestpractices.com/