Range does not take an Range object.

Discussion in 'Ruby' started by Tomoyuki Kosimizu, Nov 25, 2003.

  1. Range#include? does not take a Range object. It is strange for me.

    And, I want Range#insersect?(aRange) method.

    -net.ne.jp
    Tomoyuki Kosimizu, Nov 25, 2003
    #1
    1. Advertising

  2. Tomoyuki Kosimizu

    Dan Doel Guest

    class Range
    alias_method :eek:ld_include?, :include?

    def include?(obj)
    if obj.is_a? Range
    old_include? obj.first and
    old_include? obj.last
    else
    old_include? obj
    end
    end

    def intersect?(aRange)
    aRange.each do |i|
    return true if include? i
    end

    false
    end
    end

    p (1..4).include? 2..3

    p (1...4).include? 1..4

    p (1..6).intersect? 4..8

    p (1...6).intersect? 6..8
    Dan Doel, Nov 25, 2003
    #2
    1. Advertising

  3. Tomoyuki Kosimizu

    Dan Doel Guest

    Oops, that's slightly broken. Here's a fix.

    class Range
    alias_method :eek:ld_include?, :include?

    def include?(obj)
    if obj.is_a? Range
    old_include? obj.first and
    old_include? obj.exclude_end? ? obj.last-1 : obj.last
    else
    old_include? obj
    end
    end

    def intersect?(aRange)
    aRange.each do |i|
    return true if include? i
    end

    false
    end
    end
    Dan Doel, Nov 25, 2003
    #3
  4. I am happy that there were at least three persons (included me) who
    implemented Range#include? or intersect? incorrectly in the
    world. And, interestingly, each person implement them in different
    way.

    It seems valuable that include? and intersect? are built-in.

    greentea2fa2.so-net.ne.jp

    class Range
    alias_method :eek:riginal_include?, :include?

    def include?(other)
    return original_include?(other) unless other.is_a?(Range)
    return other.first >= first && other.last <= last
    end

    def intersect?(other)
    return true if include?(other)
    return include?(other.last) || include?(other.first) || other.include?(first) || other.include?(last)
    end
    end
    Tomoyuki Kosimizu, Nov 27, 2003
    #4
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. kai
    Replies:
    9
    Views:
    731
  2. Replies:
    4
    Views:
    8,039
    gulin
    Jun 9, 2008
  3. AMT2K5
    Replies:
    3
    Views:
    358
    Bob Hairgrove
    Dec 10, 2005
  4. newbie
    Replies:
    2
    Views:
    287
    newbie
    Jul 27, 2007
  5. Just Another Victim of the Ambient Morality

    What does it take to make an object hashable, no really...

    Just Another Victim of the Ambient Morality, Sep 13, 2006, in forum: Ruby
    Replies:
    6
    Views:
    106
    Tim Pease
    Sep 13, 2006
Loading...

Share This Page