Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"}
]
like image 673
Kavincat Avatar asked Dec 21 '16 22:12

Kavincat


People also ask

Can you sort a hash in Ruby?

Sorting Hashes in Ruby To sort a hash in Ruby without using custom algorithms, we will use two sorting methods: the sort and sort_by. Using the built-in methods, we can sort the values in a hash by various parameters.

How do I sort a hash key in Ruby?

If you want to access a Hash in a sorted manner by key, you need to use an Array as an indexing mechanism as is shown above. This works by using the Emmuerator#sort_by method that is mixed into the Array of keys. #sort_by looks at the value my_hash[key] returns to determine the sorting order.

How does hash sort work?

Hashing is a search method using the data as a key to map to the location within memory, and is used for rapid storage and retrieval. Sorting is a process of organizing data from a random permutation into an ordered arrangement, and is a common activity performed frequently in a variety of applications.


1 Answers

Here are some other ways of doing that.

x.keys.sort_by(&:to_i).each_with_object({}) { |k,h| h[k] = x[k] }
  #=> {"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"}} 

or

k = x.keys.sort_by(&:to_i)
k.zip(x.values_at(*k)).to_h

and if x is to be modified,

x.keys.sort_by(&:to_i).each { |k| x[k] = x.delete(k) }
x
like image 153
Cary Swoveland Avatar answered Oct 03 '22 18:10

Cary Swoveland