From: Rob Biedenharn Date: 2008-04-26T00:49:42+09:00 Subject: Re: Array inject function problem On Apr 25, 2008, at 11:37 AM, Jason Roelofs wrote: > On Fri, Apr 25, 2008 at 11:32 AM, Inbroker Adams > wrote: >> Hello Rubyists, >> I am new to the language and the community. >> My first problem is this : >> >> i used the following code : >> >> sum = 0 >> [1,3,5].inject() {|sum, element| sum + element} >> print sum >> >> I expected to get 9 >> but instead i get 4 >> >> I just installed the Ruby 1.8.6 one-click installer on windows >> and wrote the above commands in SciTE. >> Any suggestions?? > > You're confused with how variables work in Ruby > > puts [1,3,5].inject() {|sum, element| sum + element} # => 9 > > 'sum' in the block is a different scope from your outside 'sum' > > Jason Actually, in Ruby 1.8 the block variable sum "uses" the existing sum in the outer scope. (Ruby 1.9 will change this.) When the block is executed for the last time, sum is assigned 4 and element 5. The + gives a value of 9, but the block isn't executed after that to assign to sum again. You probably want the slightly changed: sum = [1,3,5].inject(0) {|s,e| s+e} puts sum -Rob Rob Biedenharn http://agileconsultingllc.com Rob@AgileConsultingLLC.com