Reputation: 188
array1 = [ [a], [b], [c], [d], [e] ]
array2 = [1, 2, 3, 4, 5, ...]
How can I put each of the elements of array2 into each the elements of array1 to get something like:
array3 = [ [a, 1], [b, 2], [c, 3], [d, 4], ... ]
I'm trying something like array1.map { |a| [a, array2.each { |b| b}] }
, but not really sure how to get it yet.
Thanks!
Upvotes: 2
Views: 650
Reputation: 110685
array1 = [ ['a'], ['b'], ['c'], ['d','e'] ]
array2 = [1, 2, 3, 4]
If you do not wish to alter array1
or array2
:
array1.zip(array2).map { |a1,e2| a1 + [e2] }
#=> [["a", 1], ["b", 2], ["c", 3], ["d", "e", 4]]
array1
#=> [ ['a'], ['b'], ['c'], ['d','e'] ]
If you do wish to alter array1
but not array2
:
array1.zip(array2).map { |a1,e2| a1 << e2 }
#=> [["a", 1], ["b", 2], ["c", 3], ["d", "e", 4]]
array1
#=> [["a", 1], ["b", 2], ["c", 3], ["d", "e", 4]]
If you do wish to alter array1
and can also alter array2
:
array1.map { |a| a << array2.shift }
#=> [["a", 1], ["b", 2], ["c", 3], ["d", "e", 4]]
array1
#=> [["a", 1], ["b", 2], ["c", 3], ["d", "e", 4]]
array2
#=> []
In the first two cases you could use Array#transpose instead of Array#zip by replacing array1.zip(array2)
with [array1, array2].transpose
.
Upvotes: 2
Reputation: 2359
Just try this using Array#flatten
and Array#zip
array1 = [ ['a'], ['b'], ['c'], ['d'], ['e'] ]
array2 = [1, 2, 3, 4, 5]
array1.flatten.zip(array2)
# [["a", 1], ["b", 2], ["c", 3], ["d", 4], ["e", 5]]
More information about Array#zip
can be found here.
Upvotes: 8