You could alias Array#each_value to be Array#each and then use each_value
for both types.
…which brings me to my next question… it seems strange to me that
I should be the first person to write some Ruby code who didn’t know
going into my project whether it made more sense to store my data as
an array or as a hash. Actually, I didn’t even think about it, I
simply started out with:
dataset = []
dataset << make_some_more_data()
(FWIW, my code now reads something like
dataset = Hash.new
dat = make_some_more_data()
dataset[dat.name] = dat
)
and later, when I looked at the resulting data and code, I realized
that I really wanted to index my data by it’s name, rather than some
arbitrary numeric index. But, at that point, I had written other code
that looked like
dataset.each {|x| do_something(x)}
Again, I didn’t think too much about this as I wrote that code – I
just wanted to iterate over the data I had accumulated. Later, when I
realized that I wanted to index into my data by it’s name, I thought,
“Gee, this is Ruby – I should be able to just change that to a hash
and be able to do that. I don’t care about the index anywhere in my
code.” But I realized (immediately) that Hash#each didn’t do the same
thing as Array#each. (Fortunately, my code base was small and trivial
enough, that I could change #each to #each_value, but it made me
wonder what I should have done differently to begin with, and how I
would have handled this case if the code base weren’t so small and
trivial.)
With that long winded setup… here is the next question I promised
you…
What do other folks do in this situation?
Are you all just smarter/more experienced with Ruby/ than I am and
have learned (perhaps through bitter experience) that storing things
in a Hash is better than storing them in an array when you are just
prototyping some code, not knowing where it will eventually lead? Do
you all know of the secret Array#each_element iterator which does the
same thing as the Hash#each_element iterator and you just use that?
On a related note…
Would it make sense to propose adding an Array#each_value, aliased to
Array#each to the baseline language/library definition so that one
could use the same iterator independent of whether the underlying
container were a Hash or an Array? Would it make sense to propose
adding an #each_element iterator to both classes?
–wpd