OK, looking at the archives I know this was discussed a few years ago,
but there seems to be no real conclusion or improvement since then.
The problem: Hash#each_with_index returns an index that is not usable
to address the hash. That is, given the following:
h = Hash.new
h.each_with_index {
> o, i |
...
}
i is not defined such that h[i] == o, which is both misleading and
seemingly useless. (This behavior, as per the previous discussion, can
be achieved with h.to_a.each_with_index.)
Would it not be more useful to adopt the definiton of
Enumerable#each_with_index where the index given is such that e[i] == o
for any given Enumerable?
A specific example of where this is useful is in my current codebase,
where I add _pre_store to Enumerable, for Marshalling objects. This
walks through (using each_with_index) the Enumerable, replacing indices
that refer to persistant objects with temporary references, to be
restored on load.
Given the current definition, which returns only numeric indices, this
makes any Enumerable subclass that does not use numeric indices not
follow this pattern, thus requiring specific coding. This seems like a
waste. Enumerable provides no other interface for obtaining addressable
indices.
Since containers like this all mixin Enumerable, it would seem that
using this definition would be much more accurate and useful… or at
least some interface in Enumerable that acted this way, such as
each_index.
···
–
Ryan Pavlik rpav@users.sf.net
“Now is not the time for sarcasm! Now is the time
for nefarious action.” - 8BT