简体   繁体   中英

How can i sort an arrays of hashes in ruby

this is the code i tried to sort it by name,email,country,comments.first i tried sorting by names

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)}

but the displayed output is not as i expected,it prints the same which i mentioned above.

i expected to code the final output should be like this

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

Help me to resolve these.Thanks in advance!

You should look at what element.keys(&:Name) evaluates to in the block that you're passing to #sort_by . All methods in Ruby can be given a block, you can pass it even if the method doesn't use it. Hash#keys doesn't use the block so element.keys(&:Name) is the same as element.keys and you end up trying to sort by the array ['Name', 'Email', 'Country', 'Comments'] .

If you want to sort by the name, say so:

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

Keep in mind that your keys are strings so you want element['Name'] rather than element[:Name] . I'd also recommend that you don't call your array of hashes hash , that's a little confusing.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM