Hello --
Just wondering.... What uses, if any, have people found for
Hash#each_with_index?
It actually seems a little strange to me that one can even
do this:
h = { "one" => "un", "two" => "deux", "three" => "trois" }
h.each_with_index do |e,i|
puts "#{i}: #{e[0]} #{e[1]}"
end
=>
0: one un
1: three trois
2: two deux
(And it doesn't even restore the original order, which I'd briefly
hoped it might :-)
We've been talking about the idea that arrays can be described as
hashes whose keys are constrained to be integers. And hashes can be
described as arrays whose keys (indices) don't have to be integers. I
guess what's weird about Hash#each_with_index is that it breaks the
symmetry. If a hash's keys are the equivalent of an array's indices,
then the indices that Hash#each_with_index supplies are sort of
meta-indices....
Array | Hash
|
Index/key Value | Index/key Value ???
0 "apple" | "red" "apple" 0
1 "orange" | "orange" "orange" 1
2 "banana" | "yellow" "banana" 2
What exactly *is* that last column?
Thinking out loud a little further about this:
I guess h.each_with_index is, in effect, shorthand for
h.entries.each_with_index, since the data structure that's being
indexed is not the hash but the array returned by Hash#entries.
I also guess that part of the Hash/Array asymmetry comes from the fact
that Hash#each is *already* the equivalent of Array#each_with_index --
that is, if we consider the keys and the indices to be structurally
the same.
I realize that #each_with_index comes from Enumerable, which Hash
mixes in. And, of course, Hash#each_with_index can be ignored -- it
doesn't impinge on anything one would want to do. It still strikes me
as extraneous to Hash, or non-orthagonal, or something. I'd be
interested in hearing others' views/musings.
David
--
David Alan Black
home: dblack / candle.superlink.net
work: blackdav / shu.edu
Web: http://pirate.shu.edu/~blackdav