简体   繁体   English

从数组生成哈希键和值 ruby

[英]Generating hash key and value from arrays ruby

I am trying to make a hash in Ruby that has the key/value pair from 2 arrays indexes like in the example:我试图在 Ruby 中创建一个散列,它具有来自 2 个数组索引的键/值对,如示例中所示:

hash = {
    array1[0] => array2[0]
    array1[1] => array2[1]
    array1[2] => array2[2]
}

Is there any existing method that could help me achieve this kind of result?是否有任何现有的方法可以帮助我实现这种结果?

This is actually remarkably easy.这实际上非常容易。

Let's first zip two arrays together.让我们首先将两个数组压缩在一起。

irb(main):003:0> [1, 2, 3].zip([4, 5, 6])
=> [[1, 4], [2, 5], [3, 6]]

And then we'll convert that to a hash.然后我们将其转换为哈希。

irb(main):004:0> [1, 2, 3].zip([4, 5, 6]).to_h
=> {1=>4, 2=>5, 3=>6}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM