Class: Range

Inherits:
Object show all
Includes:
ActiveSupport::CompareWithRange, ActiveSupport::EachTimeWithZone, ActiveSupport::RangeWithFormat
Defined in:
lib/active_support/core_ext/enumerable.rb,
lib/active_support/core_ext/object/json.rb,
lib/active_support/core_ext/range/overlap.rb

Overview

:nodoc:

Constant Summary

Constants included from ActiveSupport::RangeWithFormat

ActiveSupport::RangeWithFormat::RANGE_FORMATS

Instance Method Summary collapse

Methods included from ActiveSupport::EachTimeWithZone

#each, #step

Methods included from ActiveSupport::RangeWithFormat

#to_fs

Methods included from ActiveSupport::CompareWithRange

#===, #include?

Instance Method Details

#as_json(options = nil) ⇒ Object

:nodoc:



160
161
162
# File 'lib/active_support/core_ext/object/json.rb', line 160

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

#overlap?(other) ⇒ Boolean Also known as: overlaps?

Compare two ranges and see if they overlap each other

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

Returns:

  • (Boolean)


7
8
9
# File 'lib/active_support/core_ext/range/overlap.rb', line 7

def overlap?(other)
  other.begin == self.begin || cover?(other.begin) || other.cover?(self.begin)
end

#sum(initial_value = 0) ⇒ Object

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



236
237
238
239
240
241
242
243
244
245
246
247
248
# File 'lib/active_support/core_ext/enumerable.rb', line 236

def sum(initial_value = 0)
  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 = initial_value || 0
      sum + (actual_last - first + 1) * (actual_last + first) / 2
    else
      initial_value || 0
    end
  end
end