我正在使用Ruby on Rails 3.1,我希望通过关注另一个Hash
中的“声明”/“指定”顺序来订购Array
Array
个# This is the Hash of Arrays mentioned above.
hash = {
1 => [
"Value 1 1",
"Value 1 2",
"Value 1 n",
],
2 => [
"Value 2 1",
"Value 2 2",
"Value 2 n",
],
3 => [
"Value 3 1",
"Value 3 2",
"Value 3 n",
],
m => [
"Value m 1",
"Value m 2",
"Value m n",
]
}
。也就是说,例如,我有:
# This is the Array mentioned above.
array = [m, 3, 1, 2]
和
hash
我想在array
中将# Note that Hash keys are ordered as in the Array.
ordered_hash = {
m => [
"Value m 1",
"Value m 2",
"Value m n",
],
3 => [
"Value 3 1",
"Value 3 2",
"Value 3 n",
],
1 => [
"Value 1 1",
"Value 1 2",
"Value 1 n",
],
2 => [
"Value 2 1",
"Value 2 2",
"Value 2 n",
]
}
个密钥命名为“陈述”/“已指定”,以便:
Enumerable
我该怎么做(可能使用{{1}} Ruby模块或者我不熟悉的Ruby on Rails方法)?
答案 0 :(得分:3)
sorted_array = hash.sort_by { |k,v| array.index(k) }
如果你想要订购和哈希,你需要使用ActiveSupport :: OrderedHash,例如。
sorted_array = hash.sort_by { |k,v| array.index(k) }
sorted_hash = ActiveSupport::OrderedHash[sorted_array]
答案 1 :(得分:0)
在这个玩具示例中,James使用array.index
的方法会很好,但是如果哈希或数组很大,你就不想一遍又一遍.index
。更有效的方式是:
Hash[*array.map {|i| [i, hash[i]]}]