Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine two Arrays into Hash

Tags:

ruby

I've got two Arrays:

members     = ["Matt Anderson", "Justin Biltonen", "Jordan Luff", "Jeremy London"] instruments = ["guitar, vocals", "guitar", "bass", "drums"] 

What I would like to do is combine these so that the resulting data structure is a Hash like so:

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

Note the value for "Matt Anderson" is now an Array instead of a string. Any Ruby wizards care to give this a shot?

I know Hash[*members.zip(instruments).flatten] combines them almost the way I want, but what about turning the "guitars, vocals" string into an array first? Thanks.

like image 577
Michael Irwin Avatar asked Mar 02 '11 23:03

Michael Irwin


People also ask

How do I combine two arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

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.

How do I merge two arrays in Ruby?

This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).


1 Answers

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

Hash[members.zip(instruments)]  
like image 74
Raj Avatar answered Nov 11 '22 18:11

Raj