我正在使用Ruby on Rails 3.1,並且我想通過關注另一個Array
中的「陳述」/「指定」順序來訂購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
紅寶石模塊或一些未知的Ruby on Rails方法)?
注意,散列通過插入順序Ruby 1.9的排序。 – 2012-03-07 23:12:44