34

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.

4

1 回答 1

64

在 1.9 之前,枚举哈希的行为不在 ruby​​ 规范中,因此取决于实现——基本上,哈希枚举行为/模式没有被语言定义,实现真的可以做他们想做的任何事情(随机?排序?插入顺序?每次都用不同的方法?什么都行!)

1.9+,哈希枚举由语言指定按插入顺序排列,所以如果你知道你的平台是1.9+,你可以依赖它。

RubySpec

于 2013-06-28T00:29:37.717 回答