Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In <a href="http://www.ruby-doc.org/core-1.8.7/Hash.html" rel="nofollow">Ruby 1.8.7</a>, the order of elements in a hash is documented to be not under our control, so none of the above methods work. In <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html" rel="nofollow">Ruby 1.9.3</a>, things work and are documented in the way that the other answers rely upon.</p> <pre> $ irb1.8 h = { "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "spider" } Hash[h.to_a().reverse()] => {"lala"=>"54", "1"=>"spider", "10"=>"cool", "4"=>"happiness"} quit $ irb1.9.1 h = { "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "spider" } Hash[h.to_a().reverse()] =>{"1"=>"spider", "lala"=>"54", "10"=>"cool", "4"=>"happiness"} </pre> <p>The Ruby 1.8.7 way was ingrained so firmly for me that I misunderstood the question for quite some time. I thought it requested a way to <a href="http://www.ruby-doc.org/core-1.9.3/Hash.html#method-i-invert" rel="nofollow">Hash#invert</a>: ie to transform the hash such that the range maps to the domain. That method discards duplicates. Luís Ramalho proffers <a href="http://www.luisramalho.com/how-to-invert-a-hash-in-ruby-and-not-overwriting-repeated-keys" rel="nofollow">a method</a> that doesn't, but it's a bit clunky. This is a little shorter:</p> <pre> $ irb def invertWithDuplicates(original) inverse = Hash.new() { |hash, key| hash[key] = []; } original.each_pair() { |key, value| inverse[value].push(key); } return inverse end h = { "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "cool" } invertWithDuplicates(h) => {"happiness"=>["4"], "cool"=>["1", "10"], "54"=>["lala"]} </pre> <p>Sorry to drift away from the OP's intended topic, though I submit that this does fit the post's title "Reverse a hash in Ruby".</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload