key/value 对在 Ruby(或任何语言)的散列中的位置
Position of key/value pairs in a hash in Ruby (or any language)
听说hash中键值对的位置不固定,可以重新排列。
我想知道这是否属实,如果属实,有人可以指点我一些文档吗?如果错了,最好有一些相反的文档。
为了说明,如果我有以下哈希:
NUMBERS = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I",
}
一遍遍遍历,第一对key/value会不会是1000 => 'M'
?或者,key/value 对的位置是否按定义固定,必须手动更改才能更改位置?
这个问题是关于哈希质量的一个更普遍和基本的问题。我不是在问如何到达哈希中的某个位置。
通常哈希(或字典、关联数组等...)被认为是无序数据结构。
In addition, associative arrays may also include other operations such
as determining the number of bindings or constructing an iterator to
loop over all the bindings. Usually, for such an operation, the order
in which the bindings are returned may be arbitrary.
但是自 Ruby 1.9 起,散列键保持它们在 Ruby 中插入的顺序。
答案就在Ruby documentation for Hash
的顶部
Hashes enumerate their values in the order that the corresponding keys
were inserted.
在Ruby中你可以很容易地自己测试
key_indices = {
1000 => 0,
900 => 1,
500 => 2,
400 => 3,
100 => 4,
90 => 5,
50 => 6,
40 => 7,
10 => 8,
9 => 9,
5 => 10,
4 => 11,
1 => 12
}
1_000_000.times do
key_indices.each_with_index do |key_val, i|
raise if key_val.last != i
end
end
散列(也称为关联数组)是一种无序数据结构。
由于 Ruby 1.9 Ruby 保留了插入的键的顺序。
您可以在这里找到更多相关信息:
听说hash中键值对的位置不固定,可以重新排列。
我想知道这是否属实,如果属实,有人可以指点我一些文档吗?如果错了,最好有一些相反的文档。
为了说明,如果我有以下哈希:
NUMBERS = {
1000 => "M",
900 => "CM",
500 => "D",
400 => "CD",
100 => "C",
90 => "XC",
50 => "L",
40 => "XL",
10 => "X",
9 => "IX",
5 => "V",
4 => "IV",
1 => "I",
}
一遍遍遍历,第一对key/value会不会是1000 => 'M'
?或者,key/value 对的位置是否按定义固定,必须手动更改才能更改位置?
这个问题是关于哈希质量的一个更普遍和基本的问题。我不是在问如何到达哈希中的某个位置。
通常哈希(或字典、关联数组等...)被认为是无序数据结构。
In addition, associative arrays may also include other operations such as determining the number of bindings or constructing an iterator to loop over all the bindings. Usually, for such an operation, the order in which the bindings are returned may be arbitrary.
但是自 Ruby 1.9 起,散列键保持它们在 Ruby 中插入的顺序。
答案就在Ruby documentation for Hash
Hashes enumerate their values in the order that the corresponding keys were inserted.
在Ruby中你可以很容易地自己测试
key_indices = {
1000 => 0,
900 => 1,
500 => 2,
400 => 3,
100 => 4,
90 => 5,
50 => 6,
40 => 7,
10 => 8,
9 => 9,
5 => 10,
4 => 11,
1 => 12
}
1_000_000.times do
key_indices.each_with_index do |key_val, i|
raise if key_val.last != i
end
end
散列(也称为关联数组)是一种无序数据结构。 由于 Ruby 1.9 Ruby 保留了插入的键的顺序。
您可以在这里找到更多相关信息: