Ruby:一次构建一个来自字符串和两个数组值的散列 [英] Ruby: Building a hash from a string and two array values at a time
本文介绍了Ruby:一次构建一个来自字符串和两个数组值的散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
hash = {}
pre>
字符串= [one,two,three]
array = [1,2,3,4,5,6]
以便我最终得到:
hash = { one=> [1,2],
two=> [3,4],
three=> [5,6]}
我试过了:
strings.each do | string |
array.each_slice(2)do | numbers |
hash [string] = [numbers [0],numbers [1]]
end
end
但是,收益率:
hash = {one=> [5,6],two=> [5,6],三=> [5,6]}
我知道它为什么会这样做(嵌套循环),但我不知道知道如何实现我在找的东西。
解决方案如果你想要一个单行的话:
hash = Hash [strings.zip(array.each_slice(2))]
例如:
>> strings = [one,two,three]
pre>
>> array = [1,2,3,4,5,6]
>> hash = Hash [strings.zip(array.each_slice(2))]
=> {one=> [1,2],two=> [3,4],three=> [5,6]}
I'm trying to build a hash with:
hash = {} strings = ["one", "two", "three"] array = [1, 2, 3, 4, 5, 6]
so that I end up with:
hash = { "one" => [1, 2] , "two" => [3, 4] , "three" => [5, 6] }
I have tried:
strings.each do |string| array.each_slice(2) do |numbers| hash[string] = [numbers[0], numbers[1]] end end
But that yields:
hash = { "one" => [5,6] , "two" => [5,6], "three" => [5,6] }
I know why it does this (nested loops) but I don't know how to achieve what I'm looking for.
解决方案If you want a one-liner:
hash = Hash[strings.zip(array.each_slice(2))]
For example:
>> strings = ["one", "two", "three"] >> array = [1, 2, 3, 4, 5, 6] >> hash = Hash[strings.zip(array.each_slice(2))] => {"one"=>[1, 2], "two"=>[3, 4], "three"=>[5, 6]}
这篇关于Ruby:一次构建一个来自字符串和两个数组值的散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文