mercredi 21 décembre 2016

How to sort hash in rails

I have a hash

x= {
  "1"=>{:name=>"test1", :age=>"1"}, 
  "5"=>{:name=>"test2", :age=>"5"}, 
  "2"=>{:name=>"test3", :age=>"2"}, 
  "4"=>{:name=>"test4", :adn=>"4"}, 
  "3"=>{:name=>"test5", :adn=>"3"}
 }

Desired output

x= {
  "1"=>{:name=>"test1", :age=>"1"}, 
  "2"=>{:name=>"test3", :age=>"2"}, 
  "3"=>{:name=>"test5", :age=>"3"}, 
  "4"=>{:name=>"test4", :adn=>"4"}, 
  "5"=>{:name=>"test2", :adn=>"5"}
 }

What I have so far, I tried doing x.sort.flatten and i got

[
  "1", {:name=>"test1", :age=>"1"}, 
  "2", {:name=>"test3", :age=>"2"}, 
  "3", {:name=>"test5", :adn=>"3"}, 
  "4", {:name=>"test4", :adn=>"4"}, 
  "5", {:name=>"test2", :age=>"5"}
]

Aucun commentaire:

Enregistrer un commentaire