Reverse a hash in Ruby

后端 未结 9 1067
无人共我
无人共我 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:26

    if need:

    hash = {:a => :x, :b => :y, :c => :y, :d => :z}
    

    to:

    {:x => [:a], :y => [:b, c], :z => [:d] }
    

    can:

    h={};hash.to_a.each{|e|h[e[1]]||=[];h[e[1]]<

提交回复
热议问题