Array Merging into Hash

B

Bucco

Is there a simple way of merging two arrays into one has with one array
being the keys and the other being the values for the has?
a = [1, 2, 3']
b = ['a', 'b', 'c']
h = {1=>'a', 2=>'b', 3=>'c'}

Thanks:)
SA
 
G

gabriele renzi

Bucco ha scritto:
Is there a simple way of merging two arrays into one has with one array
being the keys and the other being the values for the has?
a = [1, 2, 3']
b = ['a', 'b', 'c']
h = {1=>'a', 2=>'b', 3=>'c'}
a=[1,2,3] => [1, 2, 3]
b=[:a,:b,:c] => [:a, :b, :c]
Hash[*a.zip(b).flatten]
=> {1=>:a, 2=>:b, 3=>:c}
 
M

Marcin Mielżyński

Bucco said:
Is there a simple way of merging two arrays into one has with one array
being the keys and the other being the values for the has?
a = [1, 2, 3']
b = ['a', 'b', 'c']
h = {1=>'a', 2=>'b', 3=>'c'}

a = [1, 2, 3]
b = ['a', 'b', 'c']
p a.zip(b).inject({}){|h,(k,v)| h[k]=v;h}


lopex
 
R

Robert Klemme

Marcin said:
Bucco said:
Is there a simple way of merging two arrays into one has with one array
being the keys and the other being the values for the has?
a = [1, 2, 3']
b = ['a', 'b', 'c']
h = {1=>'a', 2=>'b', 3=>'c'}

a = [1, 2, 3]
b = ['a', 'b', 'c']
p a.zip(b).inject({}){|h,(k,v)| h[k]=v;h}

Even more efficient:
require 'enumerator' => true
a = [1, 2, 3] => [1, 2, 3]
b = ['a', 'b', 'c'] => ["a", "b", "c"]
a.to_enum:)zip,b).inject({}) {|h,(k,v)| h[k]=v; h}
=> {1=>"a", 2=>"b", 3=>"c"}

Kind regards

robert
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,189
Latest member
CryptoTaxSoftware

Latest Threads

Top