Ruby:一次从字符串和两个数组值构建哈希

我正在尝试使用以下方法构建哈希:

hash = {} strings = ["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], "three" => [5,6] } 

我知道它为什么这样做(嵌套循环),但我不知道如何实现我正在寻找的东西。

如果你想要一个单行:

 hash = Hash[strings.zip(array.each_slice(2))] 

例如:

 >> 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]} 
 hash = {} strings.each { |string| hash[string] = array.slice!(0..1) } 

这是使用您熟悉的方法和技术的解决方案。 它不是一个“单线”解决方案,但如果你是新的,可能对你来说更容易理解。 第一个答案非常优雅。

正如Mu所说,Zip方法是最好的选择:

将任何参数转换为数组,然后将self的元素与每个参数的相应元素合并。 这会生成一系列self.size n元素数组,其中n比参数计数多一个。 如果任何参数的大小小于enumObj.size,则提供nil值。 如果给出了一个块,则为每个输出数组调用它,否则返回一个数组数组。