在Ruby中颠倒散列 [英] Reverse a hash in Ruby

查看:105
本文介绍了在Ruby中颠倒散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何颠倒散列中的元素,保留相同的值和键,但颠倒它们在散列中的顺序。



像这样:

  {4=> 幸福,10=> cool,lala=> 54,1=> spider} 

并将其转换为:

  {1=> 蜘蛛,拉拉=> 54,10=> 酷,4=> 幸福} 

或者,我可以运行每个向后循环,从散列中的最后一个元素开始,而不是第一个?

解决方案

您可以将哈希转换为数组,然后将其转换回哈希:

  reversed_h = Hash [h.to_a.reverse] 

Hash#to_a 给你一个数组数组,内部数组是简单的 [key,value] 对,那么你使用 Array#reverse Hash [] [key,value] 对转换回哈希。 p>

Ruby 2.1添加了 Array#to_h 方法,您现在可以说:

  reversed_h = h.to_a.reverse.to_h 


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", "10" => "cool", "lala" => "54", "1" => "spider" }

And convert that to:

{ "1" => "spider", "lala" => "54", "10" => "cool", "4" => "happiness" }

Or, perhaps I could run a each loop backwards, starting from the last element in the hash, rather than the first?

解决方案

You could convert the Hash to an Array, reverse that, and then convert it back to a Hash:

reversed_h = Hash[h.to_a.reverse]

Hash#to_a gives you an array of arrays, the inner arrays are simple [key,value] pairs, then you reverse that array using Array#reverse, and Hash[] converts the [key,value] pairs back into a Hash.

Ruby 2.1 adds an Array#to_h method so you can now say:

reversed_h = h.to_a.reverse.to_h

这篇关于在Ruby中颠倒散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆