Class: Range
- Defined in:
- lib/core_ext/enumerable.rb,
lib/core_ext/object/json.rb,
lib/core_ext/range/overlaps.rb,
lib/core_ext/range/conversions.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
-
#as_json(options = nil) ⇒ Object
:nodoc:.
-
#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)
Convert range to a formatted string.
Methods included from CoreExt::EachTimeWithZone
Methods included from CoreExt::IncludeWithRange
Instance Method Details
#as_json(options = nil) ⇒ Object
:nodoc:
135 136 137 |
# File 'lib/core_ext/object/json.rb', line 135 def as_json( = 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
5 6 7 |
# File 'lib/core_ext/range/overlaps.rb', line 5 def overlaps?(other) cover?(other.first) || other.cover?(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.
94 95 96 97 98 99 100 101 102 103 104 105 |
# File 'lib/core_ext/enumerable.rb', line 94 def sum(identity = 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 (actual_last - first + 1) * (actual_last + first) / 2 else identity end end end |
#to_formatted_s(format = :default) ⇒ Object Also known as: to_s
Convert range to a formatted string. See RANGE_FORMATS for predefined formats.
This method is aliased to to_s
.
range = (1..100) # => 1..100
range.to_formatted_s # => "1..100"
range.to_s # => "1..100"
range.to_formatted_s(:db) # => "BETWEEN '1' AND '100'"
range.to_s(:db) # => "BETWEEN '1' AND '100'"
Adding your own range formats to to_formatted_s
You can add your own formats to the Range::RANGE_FORMATS hash. Use the format name as the hash key and a Proc instance.
# config/initializers/range_formats.rb
Range::RANGE_FORMATS[:short] = ->(start, stop) { "Between #{start.to_s(:db)} and #{stop.to_s(:db)}" }
24 25 26 27 28 29 30 |
# File 'lib/core_ext/range/conversions.rb', line 24 def to_formatted_s(format = :default) if formatter = RANGE_FORMATS[format] formatter.call(first, last) else to_default_s end end |