我有一些相当复杂的排序要做。
给定一个哈希数组,我需要根据每个哈希键中的值对数组中的哈希值进行排序。
例如(以JSON格式给出):
"instruments":[
{"id":1,"title":"Piano","token":"piano","count":13},
{"id":6,"title":"Bass Guitar","token":"bass","count":12},
{"id":11,"title":"Viola","token":"viola","count":12},
{"id":4,"title":"Synth","token":"synth","count":11},
{"id":3,"title":"Keyboard","token":"keyboard","count":9},
{"id":7,"title":"Saxophone","token":"saxophone","count":8},
{"id":12,"title":"Flute","token":"flute","count":8},
{"id":5,"title":"Drums","token":"drums","count":6},
{"id":2,"title":"Guitar","token":"guitar","count":5},
{"id":8,"title":"Violin","token":"violin","count":5},
{"id":9,"title":"Vocals","token":"vocals","count":4},
{"id":10,"title":"Cello","token":"cello","count":4}
]
此JSON是Rails中responds_with
的结果。在它到达之前,我想根据每个哈希中"title"
键的字母顺序在数组中切换这些哈希值。
这是JSON(在Firebug中)的一部分的屏幕截图,以更好地说明我的意思:
非常感谢任何帮助。
谢谢!
答案 0 :(得分:4)
您正在寻找Enumerable#sort_by。
instruments.sort_by { |x| x["title"] }
答案 1 :(得分:0)
您可以使用ruby sort_by方法(http://ruby-doc.org/core-2.2.0/Enumerable.html#method-i-sort_by)
所以在你的情况下,仪器看起来像这样:
instruments=[
{"id"=>1,"title"=>"Piano","token"=>"piano","count"=>13},
{"id"=>6,"title"=>"Bass Guitar","token"=>"bass","count"=>12},
{"id"=>11,"title"=>"Viola","token"=>"viola","count"=>12},
{"id"=>4,"title"=>"Synth","token"=>"synth","count"=>11},
{"id"=>3,"title"=>"Keyboard","token"=>"keyboard","count"=>9},
{"id"=>7,"title"=>"Saxophone","token"=>"saxophone","count"=>8},
{"id"=>12,"title"=>"Flute","token"=>"flute","count"=>8},
{"id"=>5,"title"=>"Drums","token"=>"drums","count"=>6},
{"id"=>2,"title"=>"Guitar","token"=>"guitar","count"=>5},
{"id"=>8,"title"=>"Violin","token"=>"violin","count"=>5},
{"id"=>9,"title"=>"Vocals","token"=>"vocals","count"=>4},
{"id"=>10,"title"=>"Cello","token"=>"cello","count"=>4}
]
您可以使用它来按给定列(在您的情况下为“标题”)进行排序
instruments.sort_by{|instrument| instrument["title"]}
希望这有助于。
答案 2 :(得分:0)
万一它对以后的人有帮助,我的JSON是双重嵌套的
products = {
{:product=>{:id=>866468155, :code=>"TB2", :name=>"Thunderbird 2"}}
{:product=>{:id=>805953484, :code=>"FAB1", :name=>"Rolls-Royce FAB 1"}}
{:product=>{:id=>715919491, :code=>"TB1", :name=>"Thunderbird 1"}}
{:product=>{:id=>767677594, :code=>"TB5", :name=>"Thunderbird 5"}}
}
然后我就可以按名称进行排序
table.sort_by! { |x| x[:product][:name]}
...请注意,这也可以使用!进行排序,而不是创建新的数组。