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

ste*_*her 3 ruby iteration hash

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

hash = {}

strings = ["one", "two", "three"]

array = [1, 2, 3, 4, 5, 6]
Run Code Online (Sandbox Code Playgroud)

所以我最终得到:

hash = { "one" => [1, 2] ,
         "two" => [3, 4] ,
         "three" => [5, 6] }
Run Code Online (Sandbox Code Playgroud)

我试过了:

strings.each do |string|
  array.each_slice(2) do |numbers|
    hash[string] = [numbers[0], numbers[1]]
  end
end
Run Code Online (Sandbox Code Playgroud)

但那会产生:

hash = { "one" => [5,6] , "two" => [5,6], "three" => [5,6] }
Run Code Online (Sandbox Code Playgroud)

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

mu *_*ort 14

如果你想要一个单行:

hash = Hash[strings.zip(array.each_slice(2))]
Run Code Online (Sandbox Code Playgroud)

例如:

>> 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]}
Run Code Online (Sandbox Code Playgroud)

  • @steve_gallagher:[Enumerable](http://ruby-doc.org/core/Enumerable.html)是你的朋友,或者至少它是你的朋友. (2认同)