Search code examples
rubyarrayshash

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


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

Solution

  • 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]