Ruby sorts Hash by key

Of course, Hash in Ruby is similar to a set. There is no so-called order. By default, they are arranged in the order of data insertion. But you must have had such a requirement: how to rearrange the hashes in Ruby according to the order of the keys to get a new hash? Let me show you it below!

[5] pry(main)> temp = {}
=> {}
[6] pry(main)> temp["ninjas"]=36
=> 36
[7] pry(main)> temp["pirates"]=12
=> 12
[8] pry(main)> temp["cheese"]=222
=> 222
[9] pry(main)> temp
=> {"ninjas"=>36, "pirates"=>12, "cheese"=>222}

[10] pry(main)> temp.sort_by { |key, val| key }
=> [["cheese", 222], ["ninjas", 36], ["pirates", 12]]
[11] pry(main)> temp.sort_by { |key, val| key }.to_h
=> {"cheese"=>222, "ninjas"=>36, "pirates"=>12}

[12] pry(main)> temp.sort.to_h
=> {"cheese"=>222, "ninjas"=>36, "pirates"=>12}

Friendly reminder: If your Hash is very large, and your need for sorting is not very strong, it is not recommended to toss it (resource consumption and time waste will be very serious).

Guess you like

Origin blog.csdn.net/TomorrowAndTuture/article/details/112510125