Class: Range
- Inherits:
-
Object
- Object
- Range
- Defined in:
- activesupport/lib/active_support/core_ext/enumerable.rb,
activesupport/lib/active_support/core_ext/range/overlaps.rb,
activesupport/lib/active_support/core_ext/range/conversions.rb,
activesupport/lib/active_support/core_ext/range/include_range.rb,
activesupport/lib/active_support/core_ext/range/blockless_step.rb
Overview
:nodoc:
Constant Summary
- RANGE_FORMATS =
{ :db => Proc.new { |start, stop| "BETWEEN '#{start.to_s(:db)}' AND '#{stop.to_s(:db)}'" } }
Instance Method Summary (collapse)
-
- (Boolean) include_with_range?(value)
Extends the default Range#include? to support range comparisons.
-
- (Boolean) overlaps?(other)
Compare two ranges and see if they overlap each other.
-
- (Object) sum(identity = 0)
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
-
- (Object) to_formatted_s(format = :default)
(also: #to_s)
Gives a human readable format of the range.
Instance Method Details
- (Boolean) include_with_range?(value)
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 'activesupport/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 |
- (Boolean) overlaps?(other)
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 'activesupport/lib/active_support/core_ext/range/overlaps.rb', line 5 def overlaps?(other) include?(other.first) || other.include?(first) end |
- (Object) sum(identity = 0)
Optimize range sum to use arithmetic progression if a block is not given and we have a range of numeric values.
115 116 117 118 119 |
# File 'activesupport/lib/active_support/core_ext/enumerable.rb', line 115 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 |
- (Object) to_formatted_s(format = :default) 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 'activesupport/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 |