This problem boils down to one of combining sorted arrays a and b in such a way that the resulting array is sorted. A natural solution is (a+b).sort, but this is relatively inefficient, considering that a and b are already sorted. Merging two sorted arrays must be a fairly common requirement, so I gave some thought to how that could be done efficiently.
The way I settled on is very straightforward (which was somewhat of a disappointment); there may well be better (or at least cleaner) algorithms that I'm not aware of. Incidentally, I gave some thought as to whether Enumerable#slice_before could be used to advantage, but came up empty.
def merge_sorted(a,b)
sa, sb = a.size, b.size
ia = ib = 0
c = []
loop do
(return c + a[ia..-1]) if (ib == sb)
(return c + b[ib..-1]) if (ia == sa)
if a[ia] < b[ib]
c << a[ia]
ia += 1
else
c << b[ib]
ib += 1
end
end
end
merge_sorted([0, 2, 4, 6, 8], [0, 3, 6, 9])
#=> [0, 0, 2, 3, 4, 6, 6, 8, 9]