Class: Range

Inherits:
Object show all
Defined in:
activesupport/lib/active_support/core_ext/enumerable.rb,
activesupport/lib/active_support/core_ext/object/json.rb,
activesupport/lib/active_support/core_ext/range/overlaps.rb

Overview

:nodoc:

Instance Method Summary collapse

Instance Method Details

#as_json(options = nil) ⇒ Object

:nodoc:


135
136
137
# File 'activesupport/lib/active_support/core_ext/object/json.rb', line 135

def as_json(options = nil) #:nodoc:
  to_s
end

#overlaps?(other) ⇒ Boolean

Compare two ranges and see if they overlap each other

(1..5).overlaps?(4..6) # => true
(1..5).overlaps?(7..9) # => false

Returns:

  • (Boolean)

5
6
7
# File 'activesupport/lib/active_support/core_ext/range/overlaps.rb', line 5

def overlaps?(other)
  cover?(other.first) || other.cover?(first)
end

#sum(identity = nil) ⇒ Object

Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.


95
96
97
98
99
100
101
102
103
104
105
106
107
# File 'activesupport/lib/active_support/core_ext/enumerable.rb', line 95

def sum(identity = nil)
  if block_given? || !(first.is_a?(Integer) && last.is_a?(Integer))
    super
  else
    actual_last = exclude_end? ? (last - 1) : last
    if actual_last >= first
      sum = identity || 0
      sum + (actual_last - first + 1) * (actual_last + first) / 2
    else
      identity || 0
    end
  end
end