是红宝石。每个迭代器保证每次都给出相同的顺序相同的元素? [英] Is the .each iterator in ruby guaranteed to give the same order on the same elements every time?

查看:87
本文介绍了是红宝石。每个迭代器保证每次都给出相同的顺序相同的元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做这样的事情与列表'一':

I'm doing something like this with a list 'a':

a.each_with_index |outer, i|
  a.each_with_index |inner, j|
    if(j > i)
      # do some operation with outer and inner
    end
  end
end

如果迭代器是不会用同样的顺序,这是不行的。我不在乎什么顺序其实就是,我只需要两.each_with_index迭代器使用相同的顺序。

if the iterator is not going to use the same order, this won't work. I don't care what the order actually is, I just need for two .each_with_index iterators to use the same order.

我会假设,这将是一个数组,它有一个固定的顺序和属性我只是偏执迭代器不会用这个顺序...

I would assume that it would be a property of an array that it has a fixed order and I'm just being paranoid that the iterator wouldn't use that order...

推荐答案

这要看具体的可枚举对象您在操作上。

This depends on the specific Enumerable object you are operating on.

例如阵列将始终返回以相同的顺序的元件。但是,其他枚举对象并不保证行为这种方式。这方面的一个很好的例子是1.8,7基地哈希。这就是为什么很多框架(最著名的ActiveSupport)实施OrderedHash。

Arrays for example will always return elements in the same order. But other enumerable objects are not guaranteed to behave this way. A good example of this is the 1.8,7 base Hash. That is why many frameworks (most notably ActiveSupport) implement an OrderedHash.

一个有趣的边注:即使哈希将返回对象以相同的顺序如果散列没有之间更改每个调用。虽然许多对象的行为就这样,依靠这种微妙的很可能不是一个好主意。

One interesting side note: Even Hash will return objects in the same order if the hash has not changed between each calls. While many objects behave this way, relying on this subtlety is probably not a great idea.

所以,没有。通用每个不会总是以相同的顺序返回的对象。

So, no. The generic each will not always return objects in the same order.

P.S。现在Ruby 1.9的哈希值实际上是有序的<一个href=\"http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash\">http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash

P.S. Ruby 1.9's hashes are now actually ordered http://www.igvita.com/2009/02/04/ruby-19-internals-ordered-hash

这篇关于是红宝石。每个迭代器保证每次都给出相同的顺序相同的元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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