Combine two Arrays into Hash

As Rafe Kettler posted, using zip is the way to go.

Hash[members.zip(instruments)] 

Use map and split to convert the instrument strings into arrays:

instruments.map {|i| i.include?(',') ? (i.split /, /) : i}

Then use Hash[] and zip to combine members with instruments:

Hash[members.zip(instruments.map {|i| i.include?(',') ? (i.split /, /) : i})]

to get

{"Jeremy London"=>"drums",
 "Matt Anderson"=>["guitar", "vocals"],
 "Jordan Luff"=>"bass",
 "Justin Biltonen"=>"guitar"}

If you don't care if the single-item lists are also arrays, you can use this simpler solution:

Hash[members.zip(instruments.map {|i| i.split /, /})]

which gives you this:

{"Jeremy London"=>["drums"],
 "Matt Anderson"=>["guitar", "vocals"],
 "Jordan Luff"=>["bass"],
 "Justin Biltonen"=>["guitar"]}

Example 01

k = ['a', 'b', 'c']
v = ['aa', 'bb']
h = {}

k.zip(v) { |a,b| h[a.to_sym] = b } 
# => nil

p h 
# => {:a=>"aa", :b=>"bb", :c=>nil}

Example 02

k = ['a', 'b', 'c']
v = ['aa', 'bb', ['aaa','bbb']]
h = {}

k.zip(v) { |a,b| h[a.to_sym] = b }
p h 
# => {:a=>"aa", :b=>"bb", :c=>["aaa", "bbb"]}

Tags:

Ruby