vote up 3 vote down
star

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
flag
add comment

3 Answers:

vote up 9 vote down
check

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]
link|flag
comments (4)
vote up 1 vote down

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}
link|flag
add comment

Your Answer:

Get an OpenID
or

Not the answer you're looking for? Browse other questions tagged or ask your own question.