Ruby:一次从字符串和两个数组值构建散列 [英] Ruby: Building a hash from a string and two array values at a time

查看:21
本文介绍了Ruby:一次从字符串和两个数组值构建散列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to build a hash with:

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] }

我知道它为什么这样做(嵌套循环),但我不知道如何实现我想要的.

I know why it does this (nested loops) but I don't know how to achieve what I'm looking for.

推荐答案

如果你想要单线:

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]}

这篇关于Ruby:一次从字符串和两个数组值构建散列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆