Endless and beginless ranges

suggest change

A range doesn't need both ends. Ruby 2.6 added endless ranges, where the end is omitted, and Ruby 2.7 added beginless ranges, where the beginning is omitted:

adults = (18..)    # 18 and everything above
cheap  = (..9.99)  # everything up to 9.99
p adults.cover?(120)
p cheap.cover?(4.5)
p adults
p cheap
true
true
18..
..9.99

They make "from here on" and "up to here" conditions read naturally in slicing, case, clamp and pattern matching, and endless ranges give you an infinite counter for lazy iteration.

This article covers both kinds, plus the Range methods added since: Range#% (2.7), frozen ranges (3.0), overlap? and reverse_each for beginless ranges (3.3), and the new step semantics for non-numeric ranges (3.4). All examples were run with Ruby 4.0. For range basics see Ranges as Sequences and Iterating over a range.

What a missing end really is

A missing end is just nil. (1..) is the same object as (1..nil) and Range.new(1, nil):

r = (1..)
p r.begin, r.end
p r == (1..nil)
p r == Range.new(1, nil)
p (..5).begin
p Range.new(1, nil, true)
p (1...).exclude_end?
p (nil..nil).cover?("anything")
1
nil
true
true
nil
1...
true
true

(1..) and (1...) cover the same values, since there is no end to include or exclude. (nil..nil) is a range with no bounds at all: it covers every value.

The parentheses matter. A trailing .. at the end of a line doesn't end the expression: Ruby keeps reading on the next line, and with no warning even under -w:

limit = 1..
total = 10
p limit
p total
1..10
10

limit became 1..10 because the parser read 1..(total = 10). Always write endless ranges in parentheses: limit = (1..).

Slicing arrays and strings

Slicing is where endless and beginless ranges are used the most. a[2..] means "from index 2 to the end" and replaces the older a[2..-1]. a[..1] means "from the start up to index 1":

a = %w[a b c d e]
p a[2..]     # from index 2 to the end
p a[..1]     # first two
p a[...-1]   # all but the last
p a[-2..]    # last two

s = "hello world"
p s[6..]
p s[..4]
["c", "d", "e"]
["a", "b"]
["a", "b", "c", "d"]
["d", "e"]
"world"
"hello"

They work for assignment too, and in values_at:

a = %w[a b c d e]
a[3..] = ["X"]
p a

s = +"hello"
s[1..] = "ola"
p s

p (0..9).to_a.values_at(..2, 8..)
["a", "b", "c", "X"]
"hola"
[0, 1, 2, 8, 9]

Since Ruby 3.0 an array can also be sliced with an arithmetic sequence, which is what step and % return for integer ranges. With an endless range that gives "every n-th element from here on":

a = (0..9).to_a
p a[(1..).step(3)]
p a[(..-2) % 2]
[1, 4, 7]
[0, 2, 4, 6, 8]

Conditions: case, pattern matching and clamp

Range#=== checks cover?, so open-ended ranges work as when clauses. There's no need for a final else with a large made-up upper bound:

def age_group(age)
  case age
  when ...13 then :child
  when 13..19 then :teen
  when 65.. then :senior
  else :adult
  end
end

p [5, 13, 40, 70].map { age_group(_1) }
[:child, :teen, :adult, :senior]

The same ranges work as value patterns in pattern matching. Exclusive beginless ranges (...50) and exclusive bounded ranges (50...70) join up without gaps or overlaps, also for fractional scores:

def grade(score)
  case score
  in ...50 then "F"
  in 50...70 then "C"
  in 70...90 then "B"
  in 90.. then "A"
  end
end

p [10, 50, 75, 99, 120].map { grade(_1) }
p grade(69.5)
["F", "C", "B", "A", "A"]
"C"

Comparable#clamp accepts a range (since 2.7), and since 3.0 that range can be open on one side. That gives you a one-sided limit without min/max tricks:

p 15.clamp(..10)       # at most 10
p -3.clamp(0..)        # at least 0
p 5.clamp(1..10)
p 3.7.clamp(..2.5)
p "zebra".clamp("a".."m")

begin
  5.clamp(1...10)
rescue ArgumentError => e
  puts e.message
end
10
0
5
2.5
"m"
cannot clamp with an exclusive range

clamp is defined in Comparable, so it works for any class that includes it, but it doesn't accept exclusive ranges: there's no sensible "largest value below 10" for floats.

cover? vs include?

For conditions on open ranges, use cover? (or ===). It only compares the value with the bounds using <=>:

p ("a".."z").cover?("bb")
p ("a".."z") === "bb"
p ("a".."z").include?("bb")

p ("a"..).cover?("zz")
begin
  ("a"..).include?("zz")
rescue TypeError => e
  puts e.message
end

p (..5).include?(3)
true
true
false
true
cannot determine inclusion in beginless/endless ranges
true

include? (and its alias member?) behaves like cover? for numbers, but for other types it iterates the range with succ and looks for the value. "bb" sorts between "a" and "z", but it isn't one of the 26 strings that ("a".."z") produces. An endless string range can't be iterated to the end, so include? raises.

cover? also accepts another range and checks that it fits completely. include? treats a range argument as a single element, so it is almost never what you want there:

p (1..10).cover?(2..5)
p (1..10).cover?(2..15)
p (1..10).include?(2..5)
true
false
false

Iterating endless ranges

An endless range of integers is an infinite counter. each, map and to_a would never finish, so combine it with something that stops: first, take_while, find, zip, a break, or lazy:

p (1..).first(3)
p (1..).take_while { _1 * _1 < 30 }
p (1..).find { _1 % 7 == 0 && _1 % 5 == 0 }
p %w[a b c].zip(1..)
p (1..).lazy.map { _1 ** 2 }.reject(&:odd?).first(4)
p ("a"..).first(3)

(1..).each do |n|
  break if n > 3
  print n, " "
end
puts
[1, 2, 3]
[1, 2, 3, 4, 5]
35
[["a", 1], ["b", 2], ["c", 3]]
[4, 16, 36, 64]
["a", "b", "c"]
1 2 3 

zip(1..) is a compact way to number items starting from 1, and (1..).find replaces a loop with a manual counter. Without lazy, (1..).map { ... } would run forever, see Enumerators for lazy enumerators.

Methods that need the last element raise instead of hanging:

def t(label)
  print label, " => "
  p yield
rescue => e
  puts "#{e.class}: #{e.message}"
end

t("(1..).to_a") { (1..).to_a }
t("(1..).last") { (1..).last }
t("(1..).max") { (1..).max }
t("(1..).min") { (1..).min }
t("(1..).size") { (1..).size }
t("(1..).count") { (1..).count }
t("(1..).to_set") { require "set"; (1..).to_set }
(1..).to_a => RangeError: cannot convert endless range to an array
(1..).last => RangeError: cannot get the last element of endless range
(1..).max => RangeError: cannot get the maximum of endless range
(1..).min => 1
(1..).size => Infinity
(1..).count => Infinity
(1..).to_set => RangeError: cannot convert endless range to a set

Not everything is protected though. (1..).sum, (1..).each { } without a break, and (1..).select { } loop forever.

Iterating beginless ranges

A beginless range has no first element, so it can't be iterated forward:

def t(label)
  print label, " => "
  p yield
rescue => e
  puts "#{e.class}: #{e.message}"
end

t("(..5).each") { (..5).each { } }
t("(..5).to_a") { (..5).to_a }
t("(..5).min") { (..5).min }
t("(..5).max") { (..5).max }
t("(...5).max") { (...5).max }
t("(..5).size") { (..5).size }
t("(..5).reverse_each") { (..5).reverse_each.first(3) }
t("(1..).reverse_each") { (1..).reverse_each.first(3) }
(..5).each => TypeError: can't iterate from NilClass
(..5).to_a => TypeError: can't iterate from NilClass
(..5).min => RangeError: cannot get the minimum of beginless range
(..5).max => 5
(...5).max => 4
(..5).size => TypeError: can't iterate from NilClass
(..5).reverse_each => [5, 4, 3]
(1..).reverse_each => TypeError: can't iterate from NilClass

Since Ruby 3.3, reverse_each on a beginless range with an Integer end counts down from the end forever. It's the mirror image of (1..).each: combine it with first or break. It only works for integers, (..'e').reverse_each raises TypeError.

Range#size since Ruby 3.4

size returns the number of elements without iterating. Ruby 3.4 made it stricter: it now raises TypeError for ranges that can't be iterated, such as ranges starting with a Float, where older versions returned a number. For non-numeric ranges it returns nil, and count is the method that actually iterates:

def t(label)
  print label, " => "
  p yield
rescue => e
  puts "#{e.class}: #{e.message}"
end

t("(1..10).size") { (1..10).size }
t("(1.5..3).size") { (1.5..3).size }
t("(1.5..).size") { (1.5..).size }
t("('a'..'z').size") { ("a".."z").size }
t("('a'..'z').count") { ("a".."z").count }
(1..10).size => 10
(1.5..3).size => TypeError: can't iterate from Float
(1.5..).size => TypeError: can't iterate from Float
('a'..'z').size => nil
('a'..'z').count => 26

step and %

step(n) yields every n-th element. For numeric ranges it returns an Enumerator::ArithmeticSequence (since 2.6), and Range#% (since 2.7) is an alias for it:

p (1..10).step(3).to_a
p ((1..10) % 3).to_a
p (1..10).step(3)
p ((1..) % 5).first(3)
p (0.5..).step(0.5).first(3)
p (10..1).step(-3).to_a
p (1..10).step(2).size
[1, 4, 7, 10]
[1, 4, 7, 10]
((1..10).step(3))
[1, 6, 11]
[0.5, 1.0, 1.5]
[10, 7, 4, 1]
5

A beginless range can't be stepped, since there is no starting point: (..10).step(2).first(3) raises TypeError.

step with + for non-numeric ranges (Ruby 3.4)

Before Ruby 3.4, step on a non-numeric range only accepted an integer and meant "call succ n times". Since 3.4, step(x) works by repeatedly adding x to the beginning with +, and stopping when the value passes the end. Any type that has + and <=> can be stepped, and Time and Date ranges just work:

require "date"

t0 = Time.utc(2026, 1, 1)
p (t0..t0 + 120).step(60).to_a
p (t0..).step(3600).first(2)

oct = Date.new(2026, 10, 1)..Date.new(2026, 10, 31)
p oct.step(7).map(&:to_s)
p (Date.new(2026, 10, 1)..).step(7).first(2).map(&:to_s)
[2026-01-01 00:00:00 UTC, 2026-01-01 00:01:00 UTC, 2026-01-01 00:02:00 UTC]
[2026-01-01 00:00:00 UTC, 2026-01-01 01:00:00 UTC]
["2026-10-01", "2026-10-08", "2026-10-15", "2026-10-22", "2026-10-29"]
["2026-10-01", "2026-10-08"]

The step is whatever + accepts: seconds for Time, days for Date. See also Range between dates.

Your own classes only need + and <=>. They don't need succ, which a type like money doesn't have a natural answer for:

Money = Data.define(:cents) do
  include Comparable
  def <=>(other) = cents <=> other.cents
  def +(other) = Money.new(cents + other.cents)
  def inspect = format("$%.2f", cents / 100.0)
end

prices = Money.new(0)..Money.new(1000)
p prices.step(Money.new(250)).to_a
p (Money.new(0)..).step(Money.new(250)).first(3)
p prices === Money.new(5)

begin
  prices.each { }
rescue TypeError => e
  puts e.message
end
[$0.00, $2.50, $5.00, $7.50, $10.00]
[$0.00, $2.50, $5.00]
true
can't iterate from Money

The step must be something the begin value can add: prices.step(1) would fail with NoMethodError inside +, because Integer has no cents.

String ranges are the exception. For backwards compatibility, step with an integer still means "every n-th succ", while a string step uses + (concatenation):

p ("a".."e").step(2).to_a
p ("a".."aaa").step("a").to_a
p ("a".."e").step(2).class
["a", "c", "e"]
["a", "aa", "aaa"]
Enumerator

For non-numeric ranges step returns a plain Enumerator, not an ArithmeticSequence, so it can't be used to slice arrays.

overlap? (Ruby 3.3)

Range#overlap? checks whether two ranges share at least one value. It understands exclusive ends and open ranges, which makes it handy for checking schedules, reservations or version constraints:

p (1..5).overlap?(5..7)
p (1...5).overlap?(5..7)
p (..5).overlap?(3..)
p (1..5).overlap?(7..3)   # empty range
p (1...1).overlap?(1..1)  # empty range

begin
  (1..5).overlap?(3)
rescue TypeError => e
  puts e.message
end
true
false
true
false
false
wrong argument type Integer (expected Range)

1...5 ends before 5, so it doesn't touch 5..7. Empty ranges never overlap anything. To test a single value, use cover?.

A typical use is booking slots stored as exclusive time ranges, where one booking ending at 10:00 and another starting at 10:00 is fine, and an open-ended booking blocks everything after its start:

def at(h) = Time.utc(2026, 10, 18, h)

bookings = [at(9)...at(10), at(13)...at(15), at(17)..]

def free?(bookings, slot) = bookings.none? { _1.overlap?(slot) }

p free?(bookings, at(10)...at(11))
p free?(bookings, at(14)...at(16))
p free?(bookings, at(16)...at(17))
p free?(bookings, at(20)...at(21))
true
false
true
false

Ranges are frozen (Ruby 3.0)

Since Ruby 3.0, range literals and ranges made with Range.new are frozen. That makes them safe to share as constants and between Ractors:

p (1..2).frozen?
p (1..).frozen?
p Range.new(1, 2).frozen?

begin
  (1..2).instance_variable_set(:@note, "x")
rescue FrozenError => e
  puts e.message
end

p Class.new(Range).new(1, 2).frozen?
p (1..2).dup.frozen?
true
true
true
can't modify frozen Range: 1..2
false
false

Instances of Range subclasses aren't frozen, and neither are copies made with dup. Code that stored extra state in a range object with instance variables has to use a subclass or a wrapper instead.

Summary

Feature Since Example
Endless range 2.6 (1..), a[2..]
Beginless range 2.7 (..10), when ...13
Range#% 2.7 ((1..10) % 3).to_a
clamp with a range 2.7, open ranges 3.0 x.clamp(0..)
Frozen ranges 3.0 (1..2).frozen? # => true
Array slicing with a step 3.0 a[(1..).step(3)]
overlap? 3.3 (..5).overlap?(3..)
reverse_each on beginless 3.3 (..5).reverse_each.first(3)
step using + 3.4 (t0..).step(3600)
size raises for non-iterable 3.4 (1.5..3).size # TypeError

Rules of thumb:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents