From: Robert Klemme Date: 2008-12-07T21:23:44+09:00 Subject: Re: Proximity searches in Ruby I played a bit around and came up with a more involved version which works with arbitrary numbers of words but still fits into a few lines of code. Another advantage is that it identifies character positions with matches in the text. Note that this allows a maximum distance between the first and the last word of (distance * (words - 1)). It could be modified pretty easily (with an additional method in Array) to keep *all* words within distance. Have fun robert #!/bin/env ruby # search words in arbitrary order where # pairs of words have a max distance between # them ProximitySearchData = Struct.new :word, :wpos, :spos def proximity_search(text, distance, *words) sdata = words.map {|w| ProximitySearchData.new w.downcase} wpos = 0 text.scan %r{\w+}i do |match| match = match.downcase pos = $`.length sdata.each do |sd| if sd.word == match sd.spos = pos sd.wpos = wpos break :change end end == :change and sdata.all? {|sd| sd.wpos} and sdata. sort_by {|sd| sd.wpos}. each_cons(2). all? {|sd1,sd2| sd2.wpos - sd1.wpos <= distance} and yield *sdata.map {|sd| sd.spos} wpos += 1 end end text = <