From: Rick DeNatale Date: 2007-03-27T07:10:30+09:00 Subject: Re: Question about if in Ruby On 3/24/07, Vince H&K wrote: > Trans wrote: > > There is one other difference. > > > > if a = 1 > > p a > > end > > > > p a if a = 1 > > > > The later does not assign the a. > > This is not exactly true (at least on ruby 1.8.6): > > irb(main):001:0> if a = 1 > irb(main):002:1> p a > irb(main):003:1> end > 1 > => nil > irb(main):004:0> p b if b = 2 > NameError: undefined local variable or method `b' for main:Object > from (irb):4 > from :0 > > It doesn't create the variable b in the same scope as the one of the > instruction. However: > > irb(main):007:0> a = 1 > => 1 > irb(main):008:0> p a if a = 2 > 2 > => nil > irb(main):009:0> a > => 2 > > It does assign it if it already exists in the current scope. Works as > well in ruby (it is not an irb artifact). In fact it DOES assign: rick@frodo:/public/rubysource/ruby1.8.5$ irb irb(main):001:0> a NameError: undefined local variable or method `a' for main:Object from (irb):1 irb(main):002:0> p a if a = 1 (irb):2: warning: found = in conditional, should be == NameError: undefined local variable or method `a' for main:Object from (irb):2 irb(main):003:0> a => 1 I think that it's more accurate to say that the difference between if a = 1 ... end and ... if a = 1 is that the latter checks for the existence of a and raises a NameError after the assignment if the variable didn't exist before. Is this a bug? Maybe. It is kind of an edge case, notice the warning indicating that you really should be using a comparison instead of an assignment. -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/