Class: Rangeable::Interval

Inherits:
Object
  • Object
show all
Defined in:
lib/rangeable/interval.rb

Overview

Immutable closed integer interval [lo, hi].

Used internally as the storage form within Rangeable::DisjointSet. Instances are produced by ‘insert` and never mutated; equality is structural so two intervals with the same `lo` / `hi` compare equal under `==`, `eql?` and `hash`.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(lo, hi) ⇒ Interval

Returns a new instance of Interval.

Raises:

  • (ArgumentError)


13
14
15
16
17
18
19
# File 'lib/rangeable/interval.rb', line 13

def initialize(lo, hi)
  raise ArgumentError, "lo (#{lo}) > hi (#{hi})" if lo > hi

  @lo = lo
  @hi = hi
  freeze
end

Instance Attribute Details

#hiObject (readonly)

Returns the value of attribute hi.



11
12
13
# File 'lib/rangeable/interval.rb', line 11

def hi
  @hi
end

#loObject (readonly)

Returns the value of attribute lo.



11
12
13
# File 'lib/rangeable/interval.rb', line 11

def lo
  @lo
end

Instance Method Details

#==(other) ⇒ Object Also known as: eql?



31
32
33
# File 'lib/rangeable/interval.rb', line 31

def ==(other)
  other.is_a?(Interval) && other.lo == lo && other.hi == hi
end

#hashObject



36
37
38
# File 'lib/rangeable/interval.rb', line 36

def hash
  [Interval, lo, hi].hash
end

#include?(coord) ⇒ Boolean

Inclusive containment check: true when ‘coord` falls inside [lo, hi].

Returns:

  • (Boolean)


22
23
24
# File 'lib/rangeable/interval.rb', line 22

def include?(coord)
  lo <= coord && coord <= hi
end

#inspectObject



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

def inspect
  "#<Rangeable::Interval lo=#{lo} hi=#{hi}>"
end

#to_aObject

Returns the interval as a 2-element array ‘[lo, hi]`.



27
28
29
# File 'lib/rangeable/interval.rb', line 27

def to_a
  [lo, hi]
end

#to_sObject



40
41
42
# File 'lib/rangeable/interval.rb', line 40

def to_s
  "[#{lo}, #{hi}]"
end