From: Thomas Wieczorek Date: 2008-01-23T06:05:12+09:00 Subject: Re: why must I initialize this variable? Hello! On Jan 22, 2008 6:40 PM, matt neuburg wrote: > Here's a simple variable initialization / scope question. In the > following code: > First of all I think that you confuse assignment(=) with comparison(==). Every operation in Ruby returns a value. In assignment the right hand side is returned > irb h = {:test => "cool"} #returns {:test => "cool"} In comparison, either true or false are returned. An assignment returns true if you don't assign _nil_ or _false_. > irb if foo = "bar" puts foo end (irb):16: warning: found = in conditional, should be == As you see, irb or running Ruby with the '-w' will give you a warning, that you used an assignment in a > h = {:test => "cool"} > k = :test > result = nil > puts "#{result}" if (result = h[k]) > I am not sure if I am right: Here it tried to get the value of result first, if it doesn't exist, an exception occurs. After looking up result, it tests the if-clause. > ...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 > Here, you assign, the assignment returns "cool", which is true and then you print out the existing variable. I hope you understand what I mean. Regards, Thomas