Reverse a hash in Ruby

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

    In Ruby 2.1+ you can combine reverse_each and to_h:

    {foo: 1, bar: 2}.reverse_each.to_h
    #=> {:bar=>2, :foo=>1}
    

提交回复
热议问题