gpt4 book ai didi

ruby - 将键数组和值数组转换为 Ruby 中的哈希

转载 作者:数据小太阳 更新时间:2023-10-29 06:31:18 25 4
gpt4 key购买 nike

我有两个这样的数组:

keys = ['a', 'b', 'c']
values = [1, 2, 3]

Ruby 中是否有一种简单的方法可以将这些数组转换为以下散列?

{ 'a' => 1, 'b' => 2, 'c' => 3 }

这是我的做法,但我觉得应该有一个内置的方法可以轻松地做到这一点。

def arrays2hash(keys, values)
hash = {}
0.upto(keys.length - 1) do |i|
hash[keys[i]] = values[i]
end
hash
end

最佳答案

以下在 1.8.7 中有效:

keys = ["a", "b", "c"]
values = [1, 2, 3]
zipped = keys.zip(values)
=> [["a", 1], ["b", 2], ["c", 3]]
Hash[zipped]
=> {"a"=>1, "b"=>2, "c"=>3}

这似乎不适用于旧版本的 Ruby (1.8.6)。以下内容应向后兼容:

Hash[*keys.zip(values).flatten]

关于ruby - 将键数组和值数组转换为 Ruby 中的哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/740732/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com