From: Brian Candler Date: 2005-07-12T18:04:03+09:00 Subject: Re: accessing index inside map On Mon, Jul 11, 2005 at 08:07:37PM +0900, David A. Black wrote: > I'm probably the person who has asked for map_with_index the most, and > I promise not to ask for *_with_index :-) > > I can understand that a general solution makes sense, though I'm still > very unclear on the whole notion of "index" as it pertains to > Enumerable. I'm joining this converstation late, but ISTM that the fundamental issue here is that one object may have multiple enumeration methods (e.g. #each and #each_with_index), but the methods in Enumerable are only able to call #each. So perhaps a solution is to be able to choose the name of the enumerator method to call. e.g. module Enumerable def altmap(meth=:each) res = [] send(meth) { |*args| res << yield(*args) } res end end a = [10,20,30,40] p a.altmap { |x| x*2 } #=> [20, 40, 60, 80] p a.altmap(:each_with_index) { |x,i| x+i } #=> [10, 21, 32, 43] h = {1=>"one", 2=>"two", 3=>"three"} p h.altmap(:each_key) { |x| x + x } #=> [2, 4, 6] p h.altmap(:each_value) { |x| x + x } #=> ["oneone", "twotwo", "threethree"] Then, Enumerable doesn't have to care about the concept of what's an "index" - conceptually we move #each_with_index into the object being enumerated, and it can provide whatever index makes sense to it. (Enumerable could still provide a default #each_with_index as it does now, though) Aside: I always found each_with_index to be odd, because we have myhash.each { |key,value| ... } myarray.each_with_index { |value,key| ... } I'd like to be able to think of an Array as a special case of Hash, where the keys just happen to be Integers starting from 0. This could be regularised if Hash#each_with_index did { |k,v| yield v,k } Regards, Brian.