在Ruby中颠倒散列 [英] Reverse a hash in 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屋!