转换键数组和值的数组在Ruby中的哈希 [英] Converting an array of keys and an array of values into a hash in Ruby
本文介绍了转换键数组和值的数组在Ruby中的哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有两个数组是这样的:
键= ['一','B','C']
值= [1,2,3]
有没有在Ruby中一个简单的方法,以这些阵列转换成以下哈希?
{'A'=> 1,'B'=> 2,'C'=> 3}
下面是我做的方式,但我觉得应该有一个内置的方法很容易做到这一点。
高清arrays2hash(键,值)
散列= {}
0.upto(keys.length - 1)做|我|
哈希[键[I] =值[I]
结束
哈希
结束
解决方案
在1.8.7以下工作:
键= [A,B,C]
值= [1,2,3]
压缩= keys.zip(值)
= GT; [[一个,1],[b的,2],[c的,3]]
哈希[压缩]
= GT; {一个=大于1,B=大于2,C=→3}
这似乎并不在旧版本的Ruby(1.8.6)的工作。下面列出的是向后兼容的:
哈希[* keys.zip(值).flatten]
I have two arrays like this:
keys = ['a', 'b', 'c']
values = [1, 2, 3]
Is there a simple way in Ruby to convert those arrays into the following hash?
{ 'a' => 1, 'b' => 2, 'c' => 3 }
Here is my way of doing it, but I feel like there should be a built-in method to easily do this.
def arrays2hash(keys, values)
hash = {}
0.upto(keys.length - 1) do |i|
hash[keys[i]] = values[i]
end
hash
end
解决方案
The following works in 1.8.7:
keys = ["a", "b", "c"]
values = [1, 2, 3]
zipped = keys.zip(values)
=> [["a", 1], ["b", 2], ["c", 3]]
Hash[zipped]
=> {"a"=>1, "b"=>2, "c"=>3}
This appears not to work in older versions of Ruby (1.8.6). The following should be backwards compatible:
Hash[*keys.zip(values).flatten]
这篇关于转换键数组和值的数组在Ruby中的哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文