Hash ordering preserved between iterations if not modified?

11,184

Prior to 1.9, behavior of enumerated hashes was not in the ruby specification and therefore was up to implementation -- basically, hash enumeration behavior/pattern was undefined by the language and implementations could really do whatever they want (random? sorted? insertion order? different method every time? anything goes!)

1.9+, hash enumeration is specified by the language to be in the order of insertion, so if you know your platform is 1.9+, you can rely on it.

RubySpec

Share:
11,184
Ryan Haining
Author by

Ryan Haining

cppitertools writing python in c++ for the greater good for (auto&& i : range(1, 10, 2)) { ... } for (auto&& [i, e] : enumerate(vec)) { ... } for (auto&& n : imap([] (int i) { return i*i; }, vec)) { ... }

Updated on June 15, 2022

Comments

  • Ryan Haining
    Ryan Haining about 2 years

    If I iterate over a hash once, then do so again without modifying the contents, are the keys guaranteed to appear in the same order?

    A quick test suggests as much:

    > h = {'a' => 1, 'b' => 2, 'c' => 3}
    > 100_000.times.map { h.to_s == h.to_s }.all?
    => true
    

    Another question, if the above is allowed, can I iterate through it changing only values, without adding any new keys, and have the ordering of the keys be unchanged?

    similar to this python question: Do dicts preserve iteration order if they are not modified?

    Unlike the proposed duplicate I'm not interested in whether the elements have a fully specified order, only the restriction that two consecutive iterations without modification provide the same sequence.