Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - putting array elements into another array in order

Tags:

arrays

ruby

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!

like image 833
Sam Shih Avatar asked Dec 30 '25 13:12

Sam Shih


1 Answers

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.

like image 185
Nafaa Boutefer Avatar answered Jan 01 '26 08:01

Nafaa Boutefer



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!