From: "David A. Black" Date: 2007-03-27T21:03:04+09:00 Subject: Re: Question about if in Ruby 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 David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)