Hash ordering preserved between iterations if not modified?

后端 未结 1 1722
走了就别回头了
走了就别回头了 2020-12-14 06:10

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:

相关标签:
1条回答
  • 2020-12-14 07:06

    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

    0 讨论(0)
提交回复
热议问题