From: Todd Benson Date: 2008-11-20T13:41:04+09:00 Subject: Re: build hash by iterating On Wed, Nov 19, 2008 at 10:01 PM, Jason Lillywhite wrote: > Botp, thanks. That is an easier way to look at it. Can I go back to this > Enumerable#inject? I understand iterating on elements of an array like > this: > > range = (1..4) > sum = range.inject(0) {|result, element| result += element } Don't use +=, just + You are injecting the result of the block and not changing the value of "result" _inside_ the block. That variable is temporary. > > #I understand inject to be doing this (where my 'i' means 'iteration'): > #sum(i=1) = 0 + 1 = 1 > #sum(i=2) = sum(i=1) + 2 = 3 > #sum(i=3) = sum(i=2) + 3 = 6 > #sum(i=4) = sum(i=3) + 4 = 10 > => sum = 10 > > #However, iterating over a hash is confusing me. Here is a simple > example: > > hash = [[:diameter, 45], [:id, 2]].inject({}) do |result, element| > result[element.first] = element.last > result > end You are not iterating over a hash here, you are iterating over the array [[:diameter, 45], [:id, 2]] > #can someone help me understand better what exactly is happening on each > iteration? > #hash(i=1) = ?? > #hash(i=2) = ?? a = 1, 2, 3, 4 #start inject with an initial empty hash h = a.inject({}) {|s, e| s[e.to_s] = e; s} #just assigns keys to values, but the keys are strings. #inject gives you the result of the block (in this case s) on each iteration as your first inserted object (s) on each go. What you do with each element and the result of the block on each iteration is up to you. I wish I could give you a better example, but there are some experts here that can probably explain it more thoroughly. Todd