From: Ken Bloom Date: 2008-04-26T01:10:13+09:00 Subject: Re: Array inject function problem On Fri, 25 Apr 2008 10:37:43 -0500, 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' This is the case in Ruby 1.9, and if it were the case here, he'd get 0, not 4. He's using 1.8, where sum in the block *is* the same sum as outside the block, so let's look at how this works. sum=0 simple enough. this could easily be done without (since it will just be overwritten), but then sum wouldn't be accessable outside the block. [1,3,5].inject() {|sum, element| sum + element} inject calls: yield 1,3 so the block runs assigning the variable sum to be 1 and the variable element to be 3. the block returns 4, but sum is not updated with that value now, inject calls: yield 4,5 (4 is the value that the block returned before) so the block runs, assigning the variable sum to be 4 and the variable element to be 5. the block returns 9. seeing as how there's no more values in the array, inject returns 9 but the block is not called again, so sum is not updated puts sum we print the last value of sum, which was 4 -- Ken (Chanoch) Bloom. PhD candidate. Linguistic Cognition Laboratory. Department of Computer Science. Illinois Institute of Technology. http://www.iit.edu/~kbloom1/