4
我正在嘗試過濾和重新排列哈希陣列。過濾器和順序由另一個字符串數組定義,這些數組表示散列的"slug"
鍵的值。生成的數組只能包含散列,其值"slug"
鍵包含在slug數組中,並按照相同的順序排序。如果我有第一個數組:按陣列鍵排列哈希陣列
data = [
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "table",
"label" => "Table Label"
},
{
"slug" => "peach",
"label" => "Peach Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
},
{
"slug" => "bread",
"label" => "Bread Label"
},
{
"slug" => "orange",
"label" => "Orange Label"
}
]
與第二陣列爲:
ordered_keys = ["orange", "lemon", "strawberry"]
話,結果應該是這樣的一個數組:
result = [
{
"slug" => "orange",
"label" => "Orange Label"
},
{
"slug" => "lemon",
"label" => "Lemon Label"
},
{
"slug" => "strawberry",
"label" => "Strawberry Label"
}
]
我設法得到只是具有此功能的過濾功能:
result = data.select{|x| ordered_keys.include? x.slug}
但我找不到一個聰明的方法來獲得有序的。有任何想法嗎?
是的!這正是我所期待的。一個聰明而簡潔的方式來獲得結果。真棒! – 2013-04-22 23:15:27