Home > OS >  Generating hash key and value from arrays ruby
Generating hash key and value from arrays ruby

Time:10-21

I am trying to make a hash in Ruby that has the key/value pair from 2 arrays indexes like in the example:

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?

CodePudding user response:

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}
  • Related