Class: RangeWithGaps

Inherits:
Object
  • Object
show all
Defined in:
lib/range_with_gaps.rb,
lib/range_with_gaps/range_math.rb,
lib/range_with_gaps/range_with_math.rb

Defined Under Namespace

Modules: RangeMath Classes: RangeWithMath

Instance Method Summary collapse

Constructor Details

#initialize(*ranges) ⇒ RangeWithGaps

Returns a new instance of RangeWithGaps.



4
5
6
7
# File 'lib/range_with_gaps.rb', line 4

def initialize(*ranges)
  @ranges = []
  ranges.each{|r| self.add r}
end

Instance Method Details

#&(o) ⇒ Object Also known as: intersection



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/range_with_gaps.rb', line 49

def &(o)
  ret = self.class.new

  case o
  when Range
    @ranges.each do |r|
      intersection = r & o
      ret.add intersection if intersection
    end
    ret
  when self.class, Enumerable
    o.each do |i|
      intersection = self & i
      ret.add intersection if intersection
    end
    ret
  else self&(o..o)
  end
end

#-(enum) ⇒ Object Also known as: difference



44
45
46
# File 'lib/range_with_gaps.rb', line 44

def -(enum)
  dup.delete(enum)
end

#==(rset) ⇒ Object



13
14
15
# File 'lib/range_with_gaps.rb', line 13

def ==(rset)
  @ranges == rset.instance_variable_get(:@ranges)
end

#add(o) ⇒ Object Also known as: <<



17
18
19
20
21
22
23
24
25
# File 'lib/range_with_gaps.rb', line 17

def add(o)
  case o
  when Range then _add(o)
  when self.class, Enumerable then o.each{|b| add b}
  else add(o..o)
  end

  return self
end

#delete(o) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/range_with_gaps.rb', line 28

def delete(o)
  case o
  when Range then _delete(o)
  when self.class, Enumerable then o.each{|s| delete s}
  else delete(o..o)
  end

  return self
end

#dupObject



9
10
11
# File 'lib/range_with_gaps.rb', line 9

def dup
  self.class.new *to_a
end

#eachObject



78
79
80
# File 'lib/range_with_gaps.rb', line 78

def each
  to_a.each{|o| yield o}
end

#empty?Boolean

Returns:

  • (Boolean)


90
91
92
# File 'lib/range_with_gaps.rb', line 90

def empty?
  @ranges.empty?
end

#entriesObject



86
87
88
# File 'lib/range_with_gaps.rb', line 86

def entries
  @ranges.map{|r| r.to_a}.flatten
end

#include?(elem) ⇒ Boolean

Returns:

  • (Boolean)


70
71
72
# File 'lib/range_with_gaps.rb', line 70

def include?(elem)
  @ranges.any?{|r| r.include? elem}
end

#sizeObject



82
83
84
# File 'lib/range_with_gaps.rb', line 82

def size
  @ranges.inject(0){|sum, n| sum + n.size}
end

#to_aObject



74
75
76
# File 'lib/range_with_gaps.rb', line 74

def to_a
  @ranges.map{ |r| r.to_range }
end

#|(enum) ⇒ Object Also known as: +, union



38
39
40
# File 'lib/range_with_gaps.rb', line 38

def |(enum)
  dup.add(enum)
end