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?
Best Answer
You could convert the Hash to an Array, reverse that, and then convert it back to a Hash:
Hash#to_a
gives you an array of arrays, the inner arrays are simple[key,value]
pairs, then you reverse that array usingArray#reverse
, andHash[]
converts the[key,value]
pairs back into a Hash.Ruby 2.1 adds an
Array#to_h
method so you can now say: