如果未修改,哈希排序在迭代之间保留? [英] Hash ordering preserved between iterations if not modified?

查看:87
本文介绍了如果未修改,哈希排序在迭代之间保留?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



一个快速测试建议,如果我迭代散列一次,然后再次做,而不修改的内容,是保证键出现在同一顺序?尽可能多:

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

另外一个问题,如果允许上面的话,我可以通过改变值来遍历它,任何新的密钥,并具有键的顺序不变?



类似于这个python问题:如果它们没有被修改,它们是否保留迭代次序?



与提出的重复项不同,我对元素是否具有完全指定的顺序不感兴趣,只有没有修改的两个连续迭代提供相同顺序的限制。



1.9+,哈希列举由语言指定为插入顺序,所以如果您知道您的平台是1.9+,那么您可以依赖就可以了。



RubySpec


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.

解决方案

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

这篇关于如果未修改,哈希排序在迭代之间保留?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆