2012-03-07 21 views
0

我正在使用Ruby on Rails 3.1,並且我想通過關注另一個Array中的「陳述」/「指定」順序來訂購HashArray。也就是說,例如,我有:對包含有關訂單條件信息的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方法)

回答

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] 
+0

注意,散列通過插入順序Ruby 1.9的排序。 – 2012-03-07 23:12:44

0

在這個玩具例如,使用array.index詹姆斯的方法,將被罰款,但如果散列或數組很大,你不想一遍又一遍做.index。更有效的方法是:

Hash[*array.map {|i| [i, hash[i]]}] 
相關問題