Reverse a hash in Ruby

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

    Alternatively, you can use reduce and merge to add the item to the front of a new hash:

    hash = { "4" => "happiness", "10" => "cool", "lala" => "54", "1" => "spider" }
    hash.reduce({}){ |memo, object| Hash[*object].merge(memo) }
    

    but, that's crazy :D

提交回复
热议问题