Reverse a hash in Ruby

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

    In pure ruby, you can do it by hash.map(&:reverse).to_h or hash.reverse_each.to_h

    In rails, you can do it by hash.invert

提交回复
热议问题