Reputation: 4473
I heard that the positions of the key value pairs in a hash are not fixed, and could be rearranged.
I would like to know if this is true, and if it is, could someone point me to some documentation? If it is wrong, it would be great to have some documentation to the contrary.
To illustrate, if I have the following hash:
NUMBERS = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I",
}
and iterate through it over and over again, would the first key/value pair possibly not be 1000 => 'M'
? Or, are the positions of the key/value pairs fixed by definition, and would have to be manually changed in order for the positions to change?
This question is a more general and basic question about the qualities of hashes. I'm not asking how to get to a certain position in a hash.
Upvotes: 0
Views: 523
Reputation: 2575
Generally hashes (or dictionaries, associative arrays etc...) are considered unordered data structures.
From Wikipedia
In addition, associative arrays may also include other operations such as determining the number of bindings or constructing an iterator to loop over all the bindings. Usually, for such an operation, the order in which the bindings are returned may be arbitrary.
However since Ruby 1.9, hash keys maintain the order in which they were inserted in Ruby.
The answer is right at the top of the Ruby documentation for Hash
Hashes enumerate their values in the order that the corresponding keys were inserted.
In Ruby you can test it yourself pretty easily
key_indices = {
1000 => 0,
900 => 1,
500 => 2,
400 => 3,
100 => 4,
90 => 5,
50 => 6,
40 => 7,
10 => 8,
9 => 9,
5 => 10,
4 => 11,
1 => 12
}
1_000_000.times do
key_indices.each_with_index do |key_val, i|
raise if key_val.last != i
end
end
Upvotes: 2
Reputation: 8656
A hash (also called associative array) is an unordered data structure. Since Ruby 1.9 Ruby keeps the order of the keys as inserted though.
You can find a whole lot more about this here: Is order of a Ruby hash literal guaranteed?
And some here https://ruby-doc.org/core-2.4.1/Hash.html
Upvotes: 1