Class: Range
- Defined in:
- activesupport/lib/active_support/core_ext/enumerable.rb,
activesupport/lib/active_support/core_ext/range/sole.rb,
activesupport/lib/active_support/core_ext/object/json.rb,
activesupport/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
-
#as_json(options = nil) ⇒ Object
:nodoc:.
-
#sole ⇒ Object
Returns the sole item in the range.
-
#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.
Methods included from ActiveSupport::RangeWithFormat
Methods included from ActiveSupport::CompareWithRange
Instance Method Details
#as_json(options = nil) ⇒ Object
:nodoc:
158 159 160 |
# File 'activesupport/lib/active_support/core_ext/object/json.rb', line 158 def as_json( = nil) # :nodoc: to_s end |
#sole ⇒ Object
Returns the sole item in the range. If there are no items, or more than one item, raises Enumerable::SoleItemExpectedError.
(1..1).sole # => 1
(2..1).sole # => Enumerable::SoleItemExpectedError: no item found
(..1).sole # => Enumerable::SoleItemExpectedError: infinite range cannot represent a sole item
10 11 12 13 14 15 16 |
# File 'activesupport/lib/active_support/core_ext/range/sole.rb', line 10 def sole if self.begin.nil? || self.end.nil? raise ActiveSupport::EnumerableCoreExt::SoleItemExpectedError, "infinite range '#{inspect}' cannot represent a sole item" end super 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.
253 254 255 256 257 258 259 260 261 262 263 264 265 |
# File 'activesupport/lib/active_support/core_ext/enumerable.rb', line 253 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 |