Class: Range

Inherits:
Object show all
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

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

Returns:

  • (Boolean)


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)
    # 1...10 includes 1..9 but it does not include 1..10.
    operator = exclude_end? && !value.exclude_end? ? :< : :<=
    include_without_range?(value.first) && value.last.send(operator, last)
  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

Returns:

  • (Boolean)


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.



122
123
124
125
126
# File 'lib/active_support/core_ext/enumerable.rb', line 122

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