1

I am trying to merge a regular array array into a nested array such that a given element of a row in the nested array is replaced with each element in the regular array but can't compile the logic into a method e.g:

a1 = [[0,0], [0,0], [0,0]]

a2 = [1,1,1]

=> [[1, 0], [1, 0], [1, 0]] or [[0, 1], [0, 1], [0, 1]]

So far I have:

 a1[0][0, a2[0]] = a2[0]
 a1[1][0, a2[1]] = a2[1]
 a1[2][0, a2[1]] = a2[2]

Which gives the required result but this needs to be wrapped in a method such that any array sizes can be used.

2
  • Use zip with map. Or map.with_index on a1 referencing a2 with the block index parameter. Commented Nov 28, 2017 at 19:47
  • You could improve your example by making the elements more varied. For example, a1 = [[0,1], [2,3],[4,5]] and a2 = [6,7,8]. Also, it's best to ask for a specific return value for your example, rather than "this or that". If you specify "this", the return value for "that" can often be easily deduced. Commented Nov 28, 2017 at 20:57

1 Answer 1

2

You can use map (with first or last, depending on which element from a1 you want to fetch) and zip

a1.map(&:first).zip(a2)
# => [[0, 1], [0, 1], [0, 1]]

Demonstration

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

2 Comments

Consider putting that in the form of a method def m(a1,a2,a1_index)....
@CarySwoveland thanks, that was exactly what I needed

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.