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.
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.
You can do it in a single assignment: my %hash; @hash{@array1} = @array2; It's a common idiom.
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).
As Rafe Kettler posted, using zip is the way to go.
Hash[members.zip(instruments)]
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