Ruby Reorder Keys In Hash

[Solved] Ruby Reorder Keys In Hash | Ruby - Code Explorer | yomemimo.com
Question : ruby reorder keys in hash

Answered by : tsboh

# First thing to note that #sort/#sort_by will return a new array. Therefore, if we want to return the sorted hash in hash format, we need to call #to_h after #sort.
hash = { a:1, bb:2, ccc:4, dddd:3, eeeee:2}
# sort on key in decending order
puts hash.sort_by {|k, v| -k.length }.to_h
> {:eeeee=>2, :dddd=>3, :ccc=>4, :bb=>2, :a=>1}
# you could do any thing to determine the sort order of the key this way
# a normal sort would work like this (in Ruby 2.1 or higher):
hash.sort.to_h

Source : | Last Update : Thu, 25 Jun 20

Answers related to ruby reorder keys in hash

Code Explorer Popular Question For Ruby