Dylan Richards Dylan Richards - 1 year ago 50
Ruby Question

Replace all zeros in array with elements of another array

Say I've got an array like this:

array_1 = [0, 0, 1, 2, 3, 0]

and another one like this:

array_2 = [4, 5, 6]

How can I create an array like this, such that each 0 in the
is replaced by the first and subsequent elements of the

[4, 5, 1, 2, 3, 6]

That is, every time we encounter a
in the first array, we'd like to replace it with the result of

Answer Source

You could do something like this, iterate and shift when you encounter a 0

array_1.each_with_index do |val, i|
  array_1[i] = array_2.shift if val == 0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download