From: Brian Candler Date: 2005-07-13T01:10:19+09:00 Subject: Re: accessing index inside map > Well, apparently we have differing opinions on this. Personally I find > the Enumerator approach simpler as it does not clutter the original's > class interface (introducing an optional parameter on each method doubles > the number of legal invocations). :-) My own interpretation of "do the simplest" includes "don't introduce any unnecessary abstractions". Arguably, the 'optional' parameter is always there; it just happens to default to :each. There are lots of similar cases in the Ruby standard library. The Enumerator stuff is new to me, since I'm still just using 1.8.2. However, I find obj.to_enum(:each_with_index) confusing; after all, obj is *already* enumerable. Making this more general, you might get obj.rename(:each=>:each_with_index).inject(0) {|sum,(a,i)| sum + a*i} Creating an object just to say "call #each_with_index instead of #each" seems wasteful unless you plan to re-use it, given that you could just call #each_with_index in the first place. However, perhaps 'to_enum' could be called something friendlier, e.g. obj.using(:each_with_index).inject(0) {|sum,(a,i)| sum + a*i} In fact, even obj.enum(:each_with_index).inject(0) {|sum,(a,i)| sum + a*i} reads better to me, as it's not stressing the creation of an intermediate object. to_foo looks like you are converting obj into something completely different, rather than just adding a temporary wrapper. From the OP's question, then, it's a question of [1,2,3,4,5,6].map(:each_with_index) { |x,i| [2,5].include?(i) ? x : x*2 } versus [1,2,3,4,5,6].enum(:each_with_index).map { |x,i| [2,5].include?(i) ? x : x*2 } I still prefer the first :-) It's a mapping operation, applied directly to an Array. > Well, I think a vote is in order. Did you consider submitting this as > RCR? I'm not familiar with the RCR process. I just thought I'd wait and see what the list members (and Matz in particular) thought. This idea seems sufficiently obvious that I guess there's some reason why it has not been implemented already. Regards, Brian.