Hi there Thanks to Robert we have something to build up on. If you only need to know whether w1 and w2 occur in the given distance within the text or not (true/false) then we can improve his algorithm and exclude the O(n^2) part: Robert Klemme wrote: > def proximity_search(text, distance, w1, w2) > w1 = w1.downcase > w2 = w2.downcase > index1 = [] > index2 = [] > > text.scan(/\w+/).each_with_index do |w,idx| > case > when w1 == w.downcase > index1 << idx > when w2 == w.downcase > index2 << idx > end > end > > found = false > > index1.each do |i1| > index2.each do |i2| > if (i1 - i2).abs <= distance > found = true > yield i1, i2 if block_given? > end > end > end > > found > end module StringProximitySearch def proximity_search(w1, w2, distance=1) w1 = w1.downcase w2 = w2.downcase idx1 = -(distance*2) idx2 = -(distance*2) scan(/\w+/).each_with_index do |w,idx| case w.downcase when w1 idx1 = idx return true if idx1-idx2 <= distance when w2 then index2 << idx idx2 = idx return true if idx2-idx1 <= distance end end false end end class String include StringProximitySearch end your_test_string.proximity_search(w1, w2, distance) NB: This code is untested. Regards Stefan -- Posted via http://www.ruby-forum.com/.