如何在ruby中对哈希数组进行排序

yc0p9oo0  于 2021-09-29  发布在  Java
关注(0)|答案(2)|浏览(309)

这是我试图按姓名、电子邮件、国家、评论对其排序的代码。首先,我尝试按姓名排序

array_of_hashes=[
  {"Name"=>"Akash","Email"=>"akash85@gmail.com","Country"=>"India",'Comments'=>"9898984523"},
  {"Email"=>"rahul@hotmail.com","Country"=>"Srilanka","Name"=>"Rahul"},
  {"Country"=>"India", "Comments"=>"3455358782","Email"=>"veera@gmail.com","Name"=>"Veera"},
  {"Name"=>"Akash","Country"=>"India",   "Email"=>"akash37@yahoo.com", "Comments"=>"8898788932"}
]
puts array_of_hashes.sort_by { |element| element.keys(&:Name)}

但显示的输出与我预期的不同,它打印的与我上面提到的相同。
我希望最终输出的代码应该是这样的

Name Email Country Comments

Akash akash37@live.com India 8898788932
Akash akash85@gmail.com India 9898984523
Rahul rahul@hotmail.com Srilanka
Veera veera@gmail.com India 3455358782

帮我解决这些问题。提前谢谢!

yzuktlbb

yzuktlbb1#

not_a_hash = [
  {"Name"=>"Akash","Email"=>"akash85@gmail.com","Country"=>"India",'Comments'=>"9898984523"},
  {"Email"=>"rahul@hotmail.com","Country"=>"Srilanka","Name"=>"Rahul"},
  {"Country"=>"India", "Comments"=>"3455358782","Email"=>"veera@gmail.com","Name"=>"Veera"},
  {"Name"=>"Akash","Country"=>"India",   "Email"=>"akash37@yahoo.com", "Comments"=>"8898788932"}
]

sorted_values = not_a_hash.map{|h| h.values_at("Name", "Email", "Country", "Comments")}.sort
hmmo2u0o

hmmo2u0o2#

你应该看看什么 element.keys(&:Name) 计算为要传递到的块中的 #sort_by . ruby中的所有方法都可以给出给定的块,您可以传递它,即使该方法不使用它。 Hash#keys 不要这样用积木 element.keys(&:Name)element.keys 最后,您尝试按数组进行排序 ['Name', 'Email', 'Country', 'Comments'] .
如果要按名称排序,请说:

hash.sort_by { |element| element['Name'] }

请记住,您的键是字符串,因此您需要 element['Name'] 而不是 element[:Name] . 我还建议不要调用哈希数组 hash ,这有点令人困惑。

相关问题