Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reverse a hash in Ruby

Tags:

hashmap

ruby

How would I reverse the elements in the hash, keeping the same values and keys, but reversing their order in the hash.

Like so:

{ "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "spider" } 

And convert that to:

{ "1" => "spider", "lala" => "54", "10" => "cool", "4" => "happiness" } 

Or, perhaps I could run a each loop backwards, starting from the last element in the hash, rather than the first?

like image 834
slyv Avatar asked Jun 03 '12 22:06

slyv


People also ask

Can you sort a Hash in Ruby?

Sorting Hashes in RubyTo 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 does Ruby calculate Hash value?

To find a hash key by it's value, i.e. reverse lookup, one can use Hash#key . It's available in Ruby 1.9+.


2 Answers

You could convert the Hash to an Array, reverse that, and then convert it back to a Hash:

reversed_h = Hash[h.to_a.reverse] 

Hash#to_a gives you an array of arrays, the inner arrays are simple [key,value] pairs, then you reverse that array using Array#reverse, and Hash[] converts the [key,value] pairs back into a Hash.

Ruby 2.1 adds an Array#to_h method so you can now say:

reversed_h = h.to_a.reverse.to_h 
like image 143
mu is too short Avatar answered Sep 19 '22 14:09

mu is too short


In Ruby 2.1+ you can combine reverse_each and to_h:

{foo: 1, bar: 2}.reverse_each.to_h #=> {:bar=>2, :foo=>1} 
like image 34
Stefan Avatar answered Sep 19 '22 14:09

Stefan