How To Reverse a Ruby Hash

It's nice and easy to reverse a ruby array. See how to easily convert a hash as well.

It's easy to reverse a Ruby array.

a = %w{ red blue green }
# => ["red", "blue", "green"]

# => ["green", "blue", "red"]

But it's not as straightforward with a hash. We have to convert it to an array, reverse it, and send it back to a hash. This works for nested hashes as well.

my_hash = {
:key_1 => 1,
:key_2 => 2,
:key_3 => [1, 2, 3],
:key_4 => {
:subkey_1 => 1,
:subkey_2 => 2
# => {:key_1=>1, :key_2=>2, :key_3=>[1, 2, 3], :key_4=>{:subkey_1=>1, :subkey_2=>2}}

new_hash = Hash[my_hash.to_a.reverse].to_hash
# => {:key_4=>{:subkey_1=>1, :subkey_2=>2}, :key_3=>[1, 2, 3], :key_2=>2, :key_1=>1}

If you want to keep it simple, you can add a method to the Hash class.

class Hash

def reverse


Then you could do this:

# => {:key_4=>{:subkey_1=>1, :subkey_2=>2}, :key_3=>[1, 2, 3], :key_2=>2, :key_1=>1}

Let's Connect

Keep Reading

Check if a File is Binary or Text in Ruby

Here's a cool little trick to determining if a file is text or binary in Ruby just by using the path to that file.

Dec 15, 2014

Round to the nearest 0.5 in Ruby

A cool and quick trick to round floats to the nearest 0.5 in Ruby.

Nov 01, 2014

Search and Replace Multiple Lines in Multiple Files in Ruby

There are many tools for searching and replacing, but most don't support changing multiple lines in one process.

Jul 02, 2018