From: Brian Candler Date: 2005-07-13T19:35:05+09:00 Subject: Re: accessing index inside map > [1]; obj.enum(:each_with_index).inject(0) {|sum,(a,i)| sum + a*i} > > [2]; i=-1; obj.inject(0) {|sum, a| sum + a*(i+=1)} > > Can anyone shade me in on what, if any, advantage [1] has over [2]: > -- in terms of: > > a) Readability > b) Ease of use and understanding > c) Performance > d) Flexibility > e) Accuracy > f) Memory usage > g) Anything else you care to throw in ;-) 1. It retains the enapsulation of "iterating with an index"; you are reimplementing it in your inner block. (Violation of DRY principle). 2. It's more general; it works with other iteration methods. Consider Hash#each_value and Hash#each_key, or String#each_byte for example. require 'enumerator' "abc".to_enum(:each_byte).collect #=> [97, 98, 99] Of course you could rewrite this too, but then you're reimplementing 'collect': res = [] "abc".each_byte { |x| res << x } res 3. If you were using the index in more than one place in the inner block, it would become more verbose. i=0; obj.inject(0) { ... use i ... use i ...; i+=1 } Regards, Brian.