Reputation: 51
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.
Upvotes: 1
Views: 61
Reputation: 44581
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]]
Upvotes: 2