【发布时间】:2012-01-10 02:15:24
【问题描述】:
我正在尝试使用以下方法构建哈希:
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] }
我知道它为什么这样做(嵌套循环),但我不知道如何实现我想要的。
【问题讨论】: