2015-08-14 85 views
1

我想了解如何在需要時使用鍵和/或其子項對ruby哈希進行排序。對於例子:哈希與sub_hashs如何使用動態密鑰對Ruby哈希進行排序

two_hash = { 
    'a' => {'displayName' => "A", 'name' => "Apple", 'Association' => {'id' => '1', 'type' => 'B2'}}, 
    'c' => {'displayName' => "D", 'name' => "Banana", 'Association' => {'id' => '1', 'type' => 'B3'}}, 
    'b' => {'displayName' => "C", 'name' => "Orange", 'Association' => {'id' => '1', 'type' => 'B1'}}, 
    'd' => {'displayName' => "B", 'name' => "Kiwi", 'Association' => {'id' => '1', 'type' => 'B4'}} 
} 

目前我可以這樣排序,調用,並指定密鑰/子項進行排序。

puts (two_hash.sort_by {|h, k| k['displayName']}) 
puts (two_hash.sort_by {|h, k| k['Association']['type']}) 

我想將其轉換爲一個proc和使用它,每當我想給一個子項的輸入。

我想要它,所以我可以傳遞一個鍵或一個子鍵,它會爲我排序。像這樣,有沒有辦法在Ruby中做到這一點?

sort_stuff_method(two_hash, ['displayname']) 
sort_stuff_method(two_hash, ['Association']['type']) 

回答

2

這是你正在尋找,

def sort_stuff_method(input_hash, sort_key, sort_sub_key=nil) 
    input_hash.sort_by{|h,k| sort_sub_key.nil? ? k[sort_key] : k[sort_key][sort_sub_key]} 
end 

什麼,你可以使用它像這樣,

sort_stuff_method(input_hash, 'displayName') 
sort_stuff_method(input_hash, 'Association', 'Type') 
+0

謝謝你。這正是我所期待的。 –

3

這是做的一個方法:

def sort_em(h, *nested_keys) 
    h.sort_by { |k,v| nested_keys.reduce(v) { |g,k| g[k] } } 
end 

sort_em(two_hash, 'displayName') 
    #=> [["a", {"displayName"=>"A", "name"=>"Apple", 
    #   "Association"=>{"id"=>"1", "type"=>"B2"}}], 
    # ["d", {"displayName"=>"B", "name"=>"Kiwi", 
    #   "Association"=>{"id"=>"1", "type"=>"B4"}}], 
    # ["b", {"displayName"=>"C", "name"=>"Orange", 
    #   "Association"=>{"id"=>"1", "type"=>"B1"}}], 
    # ["c", {"displayName"=>"D", "name"=>"Banana", 
    #   "Association"=>{"id"=>"1", "type"=>"B3"}}]] 

sort_em(two_hash, 'Association', 'type') 
    #=> [["b", {"displayName"=>"C", "name"=>"Orange", 
    #   "Association"=>{"id"=>"1", "type"=>"B1"}}], 
    # ["a", {"displayName"=>"A", "name"=>"Apple", 
    #   "Association"=>{"id"=>"1", "type"=>"B2"}}], 
    # ["c", {"displayName"=>"D", "name"=>"Banana", 
    #   "Association"=>{"id"=>"1", "type"=>"B3"}}], 
    # ["d", {"displayName"=>"B", "name"=>"Kiwi", 
    #   "Association"=>{"id"=>"1", "type"=>"B4"}}]] 

這當然適用於任何數量的嵌套鍵。

相關問題