Range does not take an Range object.

T

Tomoyuki Kosimizu

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

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

(e-mail address removed)-net.ne.jp
 
D

Dan Doel

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
 
D

Dan Doel

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
 
T

Tomoyuki Kosimizu

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
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,038
Latest member
OrderProperKetocapsules

Latest Threads

Top