Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
319 views
in Technique[技术] by (71.8m points)

ruby - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...