From: Siep Korteling Date: 2008-11-07T05:51:00+09:00 Subject: Re: Finding gaps in a sorted sequence 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] > > Here's the best I can come up with > > def first_gap( seq ) > seq.each_cons(2) do |l,r| > _next = l.next > return _next if r!= _next > end > nil > end > > but it seems rather ugly. Anyone have a more elegant implementation? > > Cheers, > Pete The following does not quite meet your specs (it returns an array with all gaps, empty if there are no gaps). Anyway, here is my try: def find_gaps( ar ) (ar.first .. ar.last).to_a - ar end p find_gaps( [1,2,4,5] ) p find_gaps( ["a", "b", "d", "e", "h"] ) require 'date' d1 = Date.new(2008,11,6) d2 = Date.new(2008,11,7) d3 = Date.new(2008,11,9) puts find_gaps( [d1,d2,d3] ) => [3] => ["c", "f", "g"] => 2008-11-08 hth, Siep -- Posted via http://www.ruby-forum.com/.