From: Rick DeNatale Date: 2007-03-28T01:39:19+09:00 Subject: Re: Question about if in Ruby On 3/27/07, David A. Black wrote: > Hi -- > > On 3/26/07, Rick DeNatale wrote: > > 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. > > It's actually the 'a' in 'p a' that raises the error, not the one in > the assignment: > > true if a = 1 # no error > b = 1; p b if a = 1 # no error True of course. What's interesting is that the if a=1 doesn't create the variable, since it does have to be executed first. I wouldn't recommend actually writing code like this, but it does seem a bit inconsitent. A quirk of the ruby parser? eval? -- Rick DeNatale My blog on Ruby http://talklikeaduck.denhaven2.com/