Class: Range
- Defined in:
- lib/active_support/core_ext/enumerable.rb,
lib/active_support/core_ext/range/cover.rb,
lib/active_support/core_ext/range/overlaps.rb,
lib/active_support/core_ext/range/conversions.rb,
lib/active_support/core_ext/range/include_range.rb,
lib/active_support/core_ext/range/blockless_step.rb
Overview
:nodoc:
Constant Summary collapse
- RANGE_FORMATS =
{ :db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" } }
Instance Method Summary collapse
-
#include_with_range?(value) ⇒ Boolean
Extends the default Range#include? to support range comparisons.
-
#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.
-
#sum(identity = 0) ⇒ Object
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
-
#to_formatted_s(format = :default) ⇒ Object
(also: #to_s)
Gives a human readable format of the range.
Instance Method Details
#include_with_range?(value) ⇒ Boolean
Extends the default Range#include? to support range comparisons.
(1..5).include?(1..5) # => true
(1..5).include?(2..3) # => true
(1..5).include?(2..6) # => false
The native Range#include? behavior is untouched.
("a".."f").include?("c") # => true
(5..9).include?(11) # => false
10 11 12 13 14 15 16 17 18 |
# File 'lib/active_support/core_ext/range/include_range.rb', line 10 def include_with_range?(value) if value.is_a?(::Range) operator = exclude_end? ? :< : :<= end_value = value.exclude_end? ? last.succ : last include_without_range?(value.first) && (value.last <=> end_value).send(operator, 0) else include_without_range?(value) end 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
5 6 7 |
# File 'lib/active_support/core_ext/range/overlaps.rb', line 5 def overlaps?(other) include?(other.first) || other.include?(first) end |
#sum(identity = 0) ⇒ Object
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
112 113 114 115 116 |
# File 'lib/active_support/core_ext/enumerable.rb', line 112 def sum(identity = 0) return super if block_given? || !(first.instance_of?(Integer) && last.instance_of?(Integer)) actual_last = exclude_end? ? (last - 1) : last (actual_last - first + 1) * (actual_last + first) / 2 end |
#to_formatted_s(format = :default) ⇒ Object Also known as: to_s
Gives a human readable format of the range.
Example
[1..100].to_formatted_s # => "1..100"
11 12 13 14 15 16 17 |
# File 'lib/active_support/core_ext/range/conversions.rb', line 11 def to_formatted_s(format = :default) if formatter = RANGE_FORMATS[format] formatter.call(first, last) else to_default_s end end |