0

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.

sawa
  • 165,429
  • 45
  • 277
  • 381
Max Millington
  • 4,378
  • 4
  • 27
  • 34
  • Possible duplicate of [how to get hash values by position in ruby?](https://stackoverflow.com/questions/12155383/how-to-get-hash-values-by-position-in-ruby) – m. simon borg Aug 08 '17 at 16:01
  • 1
    Don't think it's a duplicate of that ^ question, but likely a duplicate of this one https://stackoverflow.com/questions/31418673/is-order-of-a-ruby-hash-literal-guaranteed – Max Millington Aug 08 '17 at 16:21

2 Answers2

2

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
m. simon borg
  • 2,515
  • 12
  • 20
1

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

Pascal
  • 8,464
  • 1
  • 20
  • 31