-1

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 array_1 is replaced by the first and subsequent elements of the array_2?:

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

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

1
  • Well, you have half of the answer right there. Use map and shift, with some conditionals on top. Commented Jul 8, 2016 at 20:23

2 Answers 2

5

This one is shorter but the shift method it will modify array_2 in-place.

array_1.map {|x| x == 0 ? array_2.shift : x}

The following uses an enumerator object with external iteration and will not modify any of the original arrays.

e = array_2.each
array_1.map {|x| x == 0 ? e.next : x}
Sign up to request clarification or add additional context in comments.

1 Comment

Even though the OP mentioned array_2.shift, it still should be noted that this mutates array_2.
1

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
end

1 Comment

This is incorrect. The question calls for a new array was to be created (rather than mutating array_1). Moreover, even though the OP mentioned array_2.shift, it still should be noted that this mutates array_2 as well.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.