From: Brian Adkins Date: 2008-11-07T17:28:09+09:00 Subject: Re: Finding gaps in a sorted sequence Martin DeMello writes: > On Thu, Nov 6, 2008 at 9:39 AM, Pete Hodgson wrote: >> Hi Folks, >> >> Given a sorted enumeration I need to find the first gap in a sequence. >> >> e.g. >> 3 == find_gap [1,2,4,5] >> nil == find_gap [1,2,3,4] > > irb(main):001:0> g = [1,2,3,5,6,8,9,10] > => [1, 2, 3, 5, 6, 8, 9, 10] > > irb(main):002:0> gap = g.inject {|a, e| e == a.next ? e : (break a.next)} > => 4 Beautiful. Excellent use of inject :) I would've thought this would be better performing also, but it lags the 'each' version by quite a bit: user system total real OP 3.490000 1.240000 4.730000 ( 4.755358) Brian 2.170000 0.830000 3.000000 ( 3.000508) Martin 3.320000 1.240000 4.560000 ( 4.582286) I still think I like it best though because it seems to be the most natural Ruby solution to the original problem. -- Brian Adkins http://www.lojic.com/ http://lojic.com/blog/