From: redstun Date: 2011-01-24T15:06:25+09:00 Subject: Re: Enumerable.inject_with_index? --0016e6d644733d6e7c049a91667a Content-Type: text/plain; charset=UTF-8 Cool! thanks! I was working with array, so I can write [3, 4, 5].each_with_index.inject(0) { |sum, (value, index)| sum + value * index } #=> 14 OR ary = [3, 4, 5] ary.each_index.inject(0) { |sum, index| sum + ary[index] * index } #=> 14 works like a charm :-) botp, Thank you very much! BTW, one more finding is that, puts([3, 4, 5].each_with_index.inject(0) do |sum, (value, index)| sum + value * index end) puts([3, 4, 5].each_with_index.inject(0) { |sum, (value, index)| sum + value * index }) puts [3, 4, 5].each_with_index.inject(0) { |sum, (value, index)| sum + value * index } puts [3, 4, 5].each_with_index.inject(0) do |sum, (value, index)| sum + value * index end all works but the last one, it reports TypeError: 0 is not a symbol, actually caused by the block being passed to puts instead of inject, then without a block, inject expect a symbol as argument. hum, just a note to myself. On Sun, Jan 23, 2011 at 11:10 PM, botp wrote: > On Sun, Jan 23, 2011 at 11:00 PM, botp wrote: > > (0..5).each.with_index.inject(0){|sum,(i,j)| sum+j} > > #=> 15 > > (0..5).each.with_index.inject(0){|sum,(i,j)| sum+i*j} > > #=> 55 > > sorry if that wasn't so clear. again, > > (3..5).each.with_index.inject(0){|sum,(value,index)| sum+value} > #=> 12 > > (3..5).each.with_index.inject(0){|sum,(value,index)| sum+index} > #=> 3 > > (3..5).each.with_index.inject(0){|sum,(value,index)| sum+index*value} > #=> 14 > > kind regards -botp > > --0016e6d644733d6e7c049a91667a--