我有以下数组:
names = [
{"Adriana"=>{:gender=>"female", :nationality=>"danish"}},
{"Adriane"=>{:gender=>"female", :nationality=>"danish"}},
{"Agatha"=>{:gender=>"female", :nationality=>"danish"}},
{"Adrianna"=>{:gender=>"female", :nationality=>"danish"}}
]
我如何按每个哈希的名称对这个哈希数组进行排序?
我尝试过:names.sort!
,它会抛出ArgumentError: comparison of Hash with Hash failed
。
答案 0 :(得分:5)
使用Enumerable#sort_by
方法执行以下操作。
names = [
{"Adriana"=>{:gender=>"female", :nationality=>"danish"}},
{"Adriane"=>{:gender=>"female", :nationality=>"danish"}},
{"Agatha"=>{:gender=>"female", :nationality=>"danish"}},
{"Adrianna"=>{:gender=>"female", :nationality=>"danish"}}
]
names.sort_by { |h| h.first.first }
# => [{"Adriana"=>{:gender=>"female", :nationality=>"danish"}},
# {"Adriane"=>{:gender=>"female", :nationality=>"danish"}},
# {"Adrianna"=>{:gender=>"female", :nationality=>"danish"}},
# {"Agatha"=>{:gender=>"female", :nationality=>"danish"}}]