2

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!

1
  • Is the value in array2 an index into array1, or do you want to combine the arrays according to their position in each array? Commented Apr 20, 2015 at 21:31

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

@QPaysTaxes This blog post (not mine) has a great explanation of ruby zip method.
@Sid So put it in your answer so that people (like me cough) who aren't familiar with .zip can see it right in the an-- oh, you already did. Uh. Good! Good on you. I'm gonna, uh... Be over here.
2
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.