Menu

Toshimaru's Blog

Reversing the Order of Hash Entries in Ruby

What I want to do

I’d like to convert the Hash from

{1=>:a, 2=>:b, 3=>:c}

to:

{3=>:c, 2=>:b, 1=>:a}

How to reverse the order of Hash

reverse_each.to_h is the way to reverse the order of Hash entries.

{ 1 => :a, 2 => :b, 3 => :c }.reverse_each.to_h #=> {3=>:c, 2=>:b, 1=>:a}

Or you could use to_a.reverse.to_h as well.

{ 1 => :a, 2 => :b, 3 => :c }.to_a.reverse.to_h #=> {3=>:c, 2=>:b, 1=>:a}

Just sort by the key

FYI, if you just want to sort the Hash by the key, sort.to_h can be used.

{b: 2, a: 1, x: -1, c: 3}.sort.to_h #=> {:a=>1, :b=>2, :c=>3, :x=>-1}

References

Load more