From: Justin Collins Date: 2008-01-23T06:25:20+09:00 Subject: Re: why must I initialize this variable? matt neuburg wrote: > Here's a simple variable initialization / scope question. In the > following code: > > h = {:test => "cool"} > k = :test > result = nil > puts "#{result}" if (result = h[k]) > > ...if I omit the third line (initializing "result"), I get an error. > Why? Intuitively I would have expected the second part of the 4th line > to create / initialize "result". > > Another way of understanding my confusion is to notice that this *does* > work: > > h = {:test => "cool"} > k = :test > if (result = h[k]) then puts "#{result}" end > > So evidently I'm asking about the difference between the last line of > the first example and the last line of the second example. Intuitively I > would have expected these lines to be absolutely equivalent, but clearly > they are not. I'd like to understand the difference rigorously. Thx! m I _believe_ this is because the left-hand side is parsed first, as Ruby works left to right. You will notice that the variable _does_ get initialized: irb(main):001:0> puts "#{hi}" if false => nil irb(main):002:0> puts "#{hi}" if hi = "hello" (irb):2: warning: found = in conditional, should be == NameError: undefined local variable or method `hi' for main:Object from (irb):2 from :0 irb(main):003:0> hi => "hello" But at the time (before evaluating the conditional clause) the variable does not exist. The code which is run when the conditional succeeds is what was parsed prior to evaluating the conditional. At least, that is my understanding. Of course, best not to use assignment as a conditional as it leads to confusion. -Justin