From: Florian Gross Date: 2004-09-20T22:29:41+09:00 Subject: Re: Array#index block and rdetect Robert Klemme wrote: >>That problem is already there, in the sense that such an object >>already has an #each_with_index method. I'm trying to make sense of >>the notion of "index" as part of Enumerable, though it's quite >>possible that *not* having it be part of Enumerable would be better -- >>and then classes could either define index-related methods or not. >>(That's what I meant originally about leaving #each_with_index up to >>the individual classes, like #each_index.) > Well, I think the main problem here is confusion of two different things: > numerical indexing (I'll use the term "index" for this) and lookup keys > (called "keys" hereafter). Let me propose yet another alternative. (More general than my last one.) Let .each yield(item, *more) and make all methods provided by Enumerable pass on *more. This would allow Hash#each to do this: class Hash def each loop over key => value pairs do yield(value, key) end end include Enumerable end hash = {1 => 2, 3 => 4} hash.each { |value,| puts value } hash.map { |value, key| [key, value] } # from hash to assoc array hash.inject(0) { |state, value, key| state + [value, key].hash } and Array to do this: class Array def each 0.upto(size - 1) do |index| yield(self[index], index) end end include Enumerable end array = ["hello", "nice", "world"] array.find_all { |item, index| index > 0 } array.each { |item,| p item } I still dislike the trailing comma that is needed if you don't want to use the extra information. This could be fixed by doing an arity check on blocks and not yielding the extra information when the block only wants a single argument. Also note that this means we won't have to deal with all the #map_with_index and so on trouble any more, Hash wouldn't need to virtually overwrite any method provided by Enumerable and that we can even easily make Enumerables that yield other information. (Is anybody able to think about a good use for that feature?) The biggest problem is that backwards compatibility would be severely broken if this were to be introduced. Maybe even too severely for Rite. > Kind regards > robert More regards, Florian Gross