From: steve ross Date: 2010-04-24T03:48:41+09:00 Subject: Re: Best way to write this method? On Apr 23, 2010, at 9:53 AM, Derek Cannon wrote: > > def elements_overlap?(a, b) > array = a.to_a & b.to_a > !array.empty? > end Here's a simple out-of-bounds comparison for elements_overlap? It makes the decision with, at most, two comparisons. require 'rubygems' require 'spec' def elements_overlap?(a, b) !((b.first > a.last) || (a.first > b.last)) end describe "overlapping" do before(:each) do @a = [1, 2, 3, 4, 5] end it "should overlap if a begins before b, but ends during b" do elements_overlap?([1, 2, 3, 4, 5], [2, 3, 4, 5, 6]).should be(true) end it "should overlap if a begins after b, but ends after b" do elements_overlap?([4, 5, 6, 7], [2, 3, 4, 5, 6]).should be(true) end it "should overlap if a begins after b and ends before b" do elements_overlap?([4, 5], [2, 3, 4, 5, 6]).should be(true) end it "should overlap if a begins before b and ends after b" do elements_overlap?([1, 2, 3, 4, 5, 6, 7], [2, 3, 4, 5, 6]).should be(true) end it "should not overlap if a begins before b and ends before b" do elements_overlap?([1, 2], [3, 4, 5, 6]).should be(false) end it "should not overlap if a begins after b and ends after b" do elements_overlap?([7, 8], [3, 4, 5, 6]).should be(false) end end