Reputation: 3077
According to the ruby-doc: "Hashes enumerate their values in the order that the corresponding keys were inserted."
Does this mean that hashes are indeed ordered like arrays, such that I can count on the indices of my_hash.keys and my_hash.values and my_hash.to_a always lining up?
For example is something like this a good or a bad idea?
my_hash = {"a"=>"alpha", "b"=>"beta", "c"=>"gamma"}
some_letters.each { |letter|
if my_hash.has_key? letter then
imp_index = my_hash.keys.find_index
table.row[r].col[imp_index].value = my_hash.values[imp_index]
end
}
so... can I treat the implicit index of an item in the my_hash.keys as an explicit attribute?
edit: also would there be any time saved by caching the .keys and .values arrays before the loop?
Upvotes: 0
Views: 69
Reputation: 99921
Hashes enumerate their values in the order that the corresponding keys were inserted
Only in Ruby 1.9. In previous version hashes are unordered.
Does this mean that I can count on the indices of my_hash.keys and my_hash.values and my_hash.to_a always lining up?
Yes, as long as iterating twice on the same unmodified hash iterates in the same order. (Even if the hash is unordered.)
Upvotes: 1