Module: CoreExtensions::Range::Operations

Includes:
Checks
Defined in:
lib/core_extensions/range/operations.rb

Defined Under Namespace

Modules: ClassMethods

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Checks

#beginless?, #endless?, #overlaps?

Class Method Details

.included(klass) ⇒ Object



10
11
12
# File 'lib/core_extensions/range/operations.rb', line 10

def self.included(klass)
  klass.extend(ClassMethods)
end

Instance Method Details

#-(other) ⇒ Array<Range>



43
44
45
# File 'lib/core_extensions/range/operations.rb', line 43

def -(other)
  self.class.subtract(self, other)
end

#merge(other) ⇒ Array<Range>



52
53
54
# File 'lib/core_extensions/range/operations.rb', line 52

def merge(other)
  self.class.merge(self, other)
end

#to_closed_range(delta: 1) ⇒ Range

Returns a range whose end is included in the range.

Examples:

Convert an open time range to a closed time range.

(Time.new(2020)...Time.new(2021)).to_closed_range #=> 2020-01-01 00:00:00 -0800..2020-12-31 23:59:59 -0800

Convert an open time range to a closed time range and specify the delta.

(Time.new(2020)...Time.new(2021)).to_closed_range(delta: Float::EPSILON)
#=> 2020-01-01 00:00:00 -0800..2020-12-31 23:59:59 4503599627370495/4503599627370496 -0800


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

def to_closed_range(delta: 1)
  return self unless exclude_end?

  if delta.is_a?(Proc)
    (self.begin..(delta.call(self.end)))
  else
    (self.begin..self.end - delta)
  end
end