Reverse a hash in Ruby

后端 未结 9 1060
无人共我
无人共我 2021-02-06 23:22

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         


        
9条回答
  •  野性不改
    2021-02-06 23:33

    h = { "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "spider" }
    p Hash[h.reverse_each.map{|e| e}]
    #=> {"1"=>"spider", "lala"=>"54", "10"=>"cool", "4"=>"happiness"}
    

    But this leaves a bad taste (just like the other answers, which work fine just like this one). If you have to do this, it could be an indication that a Hash was not the best choice.

提交回复
热议问题