Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to "zip" two arrays into hash

Tags:

I want to "zip" two arrays into a Hash.

From:

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

To:

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

How can I do it?

like image 569
Brazhnyk Yuriy Avatar asked Apr 16 '14 15:04

Brazhnyk Yuriy


People also ask

How do I merge two arrays into a hash in Perl?

You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.

What is zip method in Ruby?

Ruby | Array zip() function Array#zip() : zip() is a Array class method which Converts any arguments to arrays, then merges elements of self with corresponding elements from each argument. Syntax: Array.zip() Parameter: Array. Return: merges elements of self with corresponding elements from each argument.


2 Answers

I would do it this way:

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

If you want symbols for keys, then:

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

In Ruby 2.1.0 or higher, you could write these as:

keys.zip(values).to_h keys.map(&:to_sym).zip(values).to_h 

As of Ruby 2.5 you can use .transform_keys:

Hash[keys.zip(values)].transform_keys { |k| k.to_sym } 
like image 129
lurker Avatar answered Oct 02 '22 14:10

lurker


Just use the single Array of the twos, and then transpose it, and generate Hash:

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

or for newer ruby version:

[keys,values].transpose.to_h 
like image 36
Малъ Скрылевъ Avatar answered Oct 02 '22 14:10

Малъ Скрылевъ