{:gender=>"female", :nationality=>"danish"}}, {"Adriane"=>{:gender=>"f-6ren">
gpt4 book ai didi

ruby - 参数错误 : comparison of Hash with Hash failed - Sorting an array of hashes by hash name

转载 作者:太空宇宙 更新时间:2023-11-03 17:34:19 30 4
gpt4 key购买 nike

我有以下数组:

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

最佳答案

只需使用 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"}}]

关于ruby - 参数错误 : comparison of Hash with Hash failed - Sorting an array of hashes by hash name,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22579633/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com