Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an array of keys and an array of values into a hash in Ruby

Tags:

I have two arrays like this:

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

Is there a simple way in Ruby to convert those arrays into the following hash?

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

Here is my way of doing it, but I feel like there should be a built-in method to easily do this.

def arrays2hash(keys, values)
  hash = {}
  0.upto(keys.length - 1) do |i|
      hash[keys[i]] = values[i]
  end
  hash
end
like image 525
Paige Ruten Avatar asked Apr 11 '09 20:04

Paige Ruten


People also ask

How do you turn an array into a hash in Ruby?

The to_h method is defined in the array class. It works to convert an array to a hash in the form of key-value pairs. The method converts each nested array into key-value pairs. The method also accepts a block.

How do you push values into an array of hash in Ruby?

Creating an array of hashes You are allowed to create an array of hashes either by simply initializing array with hashes or by using array. push() to push hashes inside the array. Note: Both “Key” and :Key acts as a key in a hash in ruby.

What is the difference between a hash and an array in Ruby?

Ruby's arrays and hashes are indexed collections. Both store collections of objects, accessible using a key. With arrays, the key is an integer, whereas hashes support any object as a key.

How do you create a hash in Ruby?

In Ruby you can create a Hash by assigning a key to a value with => , separate these key/value pairs with commas, and enclose the whole thing with curly braces.


2 Answers

The following works in 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}

This appears not to work in older versions of Ruby (1.8.6). The following should be backwards compatible:

Hash[*keys.zip(values).flatten]
like image 175
Brian Campbell Avatar answered Sep 22 '22 18:09

Brian Campbell


Another way is to use each_with_index:

hash = {}
keys.each_with_index { |key, index| hash[key] = values[index] }

hash # => {"a"=>1, "b"=>2, "c"=>3}
like image 21
Matthew Schinckel Avatar answered Sep 19 '22 18:09

Matthew Schinckel