ArgumentError:Hash与Hash的比较失败 - 按散列名称对散列数组进行排序

时间:2014-03-22 15:32:32

标签: ruby arrays sorting hash

我有以下数组:

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

1 个答案:

答案 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"}}]