From: "David A. Black" Date: 2005-07-13T01:37:23+09:00 Subject: Re: accessing index inside map Hi -- On Wed, 13 Jul 2005, Brian Candler wrote: >> 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. I wonder whether one might (re)introduce the "iter[ator]" set of terms, rather than enumerator. I'm not totally clear on the relation between them, so I may be off the mark, but I was thinking of things like: obj.iterate_with(:each_with_index).inject ... a little bit on the model of sort_by. Then again, this may be getting dangerously close to the rejected RCR at http://www.rcrchive.net/rejected.html#rcr50. I have to admit I haven't totally assimilated the Enumerator mechanisms, which strike me as very useful and powerful but sort of a secondary system overlaid on the whole iterator and/or enumerable thing. I guess the barrier, for me, is having the separate Enumerator object, rather than just having it happen in the course of calling a method. I guess that's also what's powerful about it :-) > I'm not familiar with the RCR process. See http://www.rcrchive.net. David -- David A. Black dblack@wobblini.net