Module: RangeExtensions

Included in:
Range
Defined in:
lib/powertool/range.rb

Overview

Extensions to Ruby’s Range class

Instance Method Summary collapse

Instance Method Details

#each(warn_on_order_error: true) ⇒ Object



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/powertool/range.rb', line 5

def each(warn_on_order_error: true)
  return super() if first <= last || first.class != last.class

  position = first
  while position >= last
    # We always attempt pred before yielding.
    prev_position = position.clone
    begin
      position = position.pred
    rescue NoMethodError
      raise ArgumentError, "#{first.class}s do not support backwards iteration." if warn_on_order_error

      return super()
    end

    yield(prev_position)
  end
end

#sortObject



24
25
26
27
28
29
30
31
32
# File 'lib/powertool/range.rb', line 24

def sort
  begin
    return self if first <= last
  rescue NoMethodError
    raise "#{first.class}s cannot be sorted"
  end

  (last..first)
end