From: dblack@... Date: 2007-02-21T12:01:51+09:00 Subject: Re: Range#overlap? HI -- On Wed, 21 Feb 2007, bbiker wrote: > On Feb 20, 7:04 pm, dbl...@wobblini.net wrote: >> Hi -- >> >> >> >> >> >> On Wed, 21 Feb 2007, Daniel Schierbeck wrote: >>> On Wed, 2007-02-21 at 08:00 +0900, Daniel Finnie wrote: >>>> I think your implementation is cleaner however the endpoints of a Range >>>> do not have to implement #succ. >> >>>> class Range >>>> def span? other >>>> include? other.first and >>>> (other.exclude_end? ? other.last < last : other.last <= last ) >>>> end >>>> end >> >>> I've tried that implementation, but i doesn't work if you consider this >>> valid: >> >>> (4..8).span? 6...9 >> >>> Since 6...9 yields the same values as 6..8. Or am I wrong to expect the >>> above? >> >> I don't think ranges really yield values. Some of them can be >> converted to arrays, but a range qua range is really just two >> endpoints, between which everything comparable to those endpoints >> either is or isn't. >> >> I'm not sure I have my head around what span? is supposed to be doing. >> Can you write some test cases? I keep thinking of this: >> >> include?(other.first) and include?(other.last) >> >> but I don't think that's what you're trying to do with span?. >> > > Here is my entry for overlap? > > require 'facets/core/range/within' > > class Range > > # Uses the Range#within and Range#include methods to determine > # if another Range _overlap_ this Range. > # neither Range is within the other Range > # (1..3).overlap?(2..4) #=> true > # > def overlap?(other) > # |---| |---| |-----| |-----| |-----| > # |-----| |-----| |-----| |---| |---| > !self.within?(other) && !other.within?(self) && > # |-------| |------| > # |-------| |-------| > (self.include?(other.first) && other.include?(self.last) || > # |-------| |-------| > # |-------| |------| > other.include?(self.first) && self.include?(other.last)) > end > end > > > =begin test > > require 'test/unit' > > class TCRange < Test::Unit::TestCase > > def test_overlap? > assert(!(3..6).overlap?(3..6) ) > assert(!(4..5).overlap?(3..6) ) > assert(!(2..7).overlap?(3..6) ) > assert( (2..5).overlap?(3..6) ) > assert( (2..3).overlap?(3..6) ) > assert( (7..10).overlap?(6..9) ) > assert( (9..12).overlap?(6..9) ) > end > end > =end > Here's a slightly shorter method that makes all the tests pass: def overlap?(other) self.include?(other.first) &&! self.include?(other.last) or other.include?(self.first) &&! other.include?(self.last) end David -- Q. What is THE Ruby book for Rails developers? A. RUBY FOR RAILS by David A. Black (http://www.manning.com/black) (See what readers are saying! http://www.rubypal.com/r4rrevs.pdf) Q. Where can I get Ruby/Rails on-site training, consulting, coaching? A. Ruby Power and Light, LLC (http://www.rubypal.com)