How to "zip" two arrays into a hash

I want to "compress" two arrays into a hash.

From:

['BO','BR'] ['BOLIVIA','BRAZIL'] 

In order to:

 {BO: 'BOLIVIA', BR:'BRAZIL'} 

How can I do it?

+13
source share
5 answers

I would do it like this:

 keys = ['BO','BR'] values = ['BOLIVIA','BRAZIL'] Hash[keys.zip(values)] # => {"BO"=>"BOLIVIA", "BR"=>"BRAZIL"} 

If you need characters for keys, then:

 Hash[keys.map(&:to_sym).zip(values)] # => {:BO=>"BOLIVIA", :BR=>"BRAZIL"} 

In Ruby 2.1.0 or later, you can write them as:

 keys.zip(values).to_h keys.map(&:to_sym).zip(values).to_h 
+20
source

Just use a single Array of two, and then transpose it and create a Hash :

 keys = ['BO','BR'] values = ['BOLIVIA','BRAZIL'] Hash[[keys,values].transpose] # => {"BO"=>"BOLIVIA", "BR"=>"BRAZIL"} 

or for a newer version of ruby:

 [keys,values].transpose.to_h 
+4
source

Pretty readable version:

 keys = ['BO','BR'] values = ['BOLIVIA','BRAZIL'] keys.zip(values).each_with_object({}) do |(key, value), hash| hash[key.to_sym] = value end 
+2
source

Ironically, if you just cover a few dots and underscores in your question, this just works:

I want to " zip " two arrays in to_h ash

 ary1.zip(ary2).to_h # => { 'BO' => 'BOLIVIA', 'BR' => 'BRAZIL' } 

In fact, you indicated in your output hash that the keys must be Symbol not String s, so we need to convert them first:

 ary1.map(&:to_sym).zip(ary2).to_h # => { BO: 'BOLIVIA', BR: 'BRAZIL' } 
+2
source

You can make a zipped array and then convert the array to a hash, for example:

 keys = ['BO','BR'] values = ['BOLIVIA','BRAZIL'] array = key.zip(values) # => [['BO','BOLIVIA'],['BR','BRAZIL']] hash = array.to_h # => {'BO' => 'BOLIVIA','BR' => 'BRAZIL'} 
0
source

All Articles