I want to "zip" two arrays into a Hash.
From:
['BO','BR'] ['BOLIVIA','BRAZIL']
To:
{BO: 'BOLIVIA', BR:'BRAZIL'}
How can I do it?
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
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.
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 }
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With