Skip to content
Tutorials Center
My learning

Topics

Lesson 18 of 134 ยท Control Flow

Ranges

Learn Ruby ranges - inclusive and exclusive, endless and beginless ranges, step and %, each, to_a, include? versus cover?, case/when, slicing and lazy use.

A range is an object that represents an interval: everything from one value to another. 1..5 stands for the numbers one to five, "a".."e" for the letters a to e, and Time.now..Time.now + 3600 for the next hour. Ranges are small and cheap because they store only their two ends, not every value in between, so 1..1_000_000_000 costs the same memory as 1..3.

You will use ranges all the time: to loop, to slice arrays and strings, to describe ages or score brackets in case and when, to check that a value falls within limits, and to produce sequences. This lesson covers how to create them, the difference between .. and ..., endless and beginless forms, stepping, and the subtle difference between include? and cover?.

Inclusive and exclusive ranges

Two dots include the end value. Three dots stop before it.

Ruby Two dots and three dots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The exclusive form is a perfect match for zero-based indexes: 0...array.size visits every valid position and nothing more. Notice that exclusive.last returns 5 (the declared end) while exclusive.max returns 4 (the largest member). Use max when you need the real last element.

To remember which is which: the longer ... stops one step sooner. Fewer elements, more dots.

What can be a range?

Any objects that can be compared with <=> can form a range. To iterate (each, to_a), the start must also respond to succ, which gives the next value.

Ruby Ranges of numbers, letters and floats

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

String ranges follow the succ rule, so "aa".."ad" goes aa, ab, ac, ad. A Float range is only a pair of limits: it can answer "is this value inside?" but has no "next" float to step to, so each raises a TypeError with the message you can see in the output.

Making an array with to_a, and a lazy alternative

to_a (or the splat [*1..5]) builds an array of all members. Be careful with big ranges: (1..10_000_000).to_a allocates ten million objects. Iterate with each instead, which uses constant memory.

Ruby to_a versus lazy iteration

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Range#sum on integers uses the arithmetic formula, so it is instant. lazy (explained in Enumerators and Lazy Enumerators) lets you work with an infinite range by computing only the values you ask for.

Endless and beginless ranges

Leave out one end and the range becomes open on that side.

Ruby Endless and beginless

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Write an endless range at the end of a line inside parentheses: x = (10..). Without them, Ruby continues onto the next line and reads 10.. followed by the next statement as one range, which fails with bad value for range (ArgumentError) or silently builds the wrong range.

Endless ranges iterate forever, so always pair them with first(n), take, lazy, find or a break. Beginless ranges cannot be iterated at all because there is no starting point. They are for comparisons, case/when and slicing. See Slices and Indexing in Depth for more.

step and the % operator

step(n) walks a range in jumps. Ruby 3 added % as a shorter alias, which works on integer and float ranges.

Ruby Stepping through a range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Float stepping is computed from the start (start + i * step) rather than by repeated addition, so the error does not pile up the way it would in a hand-written while loop. Quarter-sized steps are exact in binary, which is why the output here looks clean.

include?, member?, cover? and ===

All of these ask "is this value in the range?", but they work differently.

  • cover? only compares with the two ends. It is fast and works for any comparable values.
  • include? and member? on numeric ranges behave like cover?. On other ranges (like string ranges) they may walk the elements.
  • === is what case/when uses. For ranges it delegates to cover?.
Ruby cover? versus include? on strings

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

"mm" sorts after "m" and before "z", so cover? says yes while include? correctly says "not one of the generated strings". For dates and times, always use cover?; they are comparable but have no cheap succ.

Using ranges in case, conditions and clamping

Ruby Brackets, validation and clamp

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Comparable#clamp accepts a range, including endless and beginless ones, to force a value into limits. See Comparable for more.

Ranges in conditions and the flip-flop

Ranges are usually written to be asked a question: (18..64).cover?(age) or when 18..64. A range in a condition can also mean something quite different. When a range's two ends are conditions (expressions that are true or false) and the range is written directly in an if, unless or ternary condition, Ruby treats it as a flip-flop: a tiny on/off switch with memory. It turns on when the first condition becomes true, stays on, and turns off after the second condition becomes true.

The classic use is picking a block of lines out of a stream, between two markers:

Ruby The flip-flop: switching on and off

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The first loop prints the two blocks, BEGIN alpha beta END and BEGIN gamma END, including both markers, and skips intro, outro and tail. The switch keeps its state between iterations, which is what makes it unusual: nothing in the code stores a variable, yet the loop "remembers" it is inside a block.

Two dots or three

Like ordinary ranges, a flip-flop comes in two forms, and the difference is about the moment of switching on:

  • a..b checks b on the same step that a turns the switch on, so a single line can start and end the range.
  • a...b does not check b until the next step.
Ruby Two dots versus three dots

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

With two dots, the first A turns the switch on and the same check immediately turns it off, so the range covers just that line (and the second A starts a new one-line range, so both A lines print). With three dots, the first A only turns it on; the switch stays on through B and ends at the second A, so A, B, A print.

Flip-flop or Range object?

The same punctuation means two things, and the context decides. In a condition, (a == 1)..(b == 2) is a flip-flop. Anywhere else, .. builds a Range object, and a range of true/false values is an error:

Ruby Outside a condition it is a Range (and this fails)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

The assignment raises ArgumentError: bad value for range, because true..false is not a range of comparable values. Remember: only a range written directly as the condition is a flip-flop.

The flip-flop is a remnant of awk and Perl, designed for scanning text. It is rarely needed in modern Ruby: it hides state, is confusing to readers and does not work well in methods that can be called again, because the switch belongs to the code location and not to the call. It was marked for removal for a while, but it remains part of Ruby 4.0 and runs without a warning. Prefer an explicit variable, which is clearer:

Ruby
inside = false
lines.each do |line|
  inside = true if line == "BEGIN"
  puts line if inside
  inside = false if line == "END"
end

For ranges as numeric or alphabetical intervals (when 1..5, cover?, slicing), the rest of this lesson is what you will use every day.

Ranges as indexes and slices

Arrays and strings accept ranges in []. Negative numbers count from the end, and ..-1 means "through the last element".

Ruby Slicing with ranges

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Notice nums[6..] is an empty array (the start equals the length), but nums[10..] is nil (the start lies beyond the end). That distinction trips people up, as discussed in Slices and Indexing in Depth.

Range methods worth knowing

Ruby Handy Range methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ranges are frozen, so they are safe to share and use as constants. Range includes Enumerable, so everything from Iterating and Transforming Arrays works on them. overlap? is a recent addition that tells you whether two ranges share any value.

Pitfalls

Precedence

A range operator binds loosely. 1..n + 1 means 1..(n + 1), but 1..n.size may not be what you expect when mixing with method calls on literals. Wrap ranges in parentheses before calling a method: (1..5).each, not 1..5.each.

Ruby Missing parentheses (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Ruby reads this as 1..(5.each { ... }) and stops with main.rb:1:in '<main>': undefined method 'each' for an instance of Integer (NoMethodError). Writing (1..5).each fixes it.

Descending ranges are empty

5..1 is a valid range, but it has no members. Use 5.downto(1), (1..5).reverse_each or a negative step.

Ruby Going down

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Off-by-one with exclusive ranges

(1...5).size is 4, and (1...5).include?(5) is false. Decide up front whether the end belongs in the range, and remember that character and date ranges follow the same rules.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is (1...5).to_a?

    Three dots exclude the end value, so the range stops at 4.
  2. 2. Why does (1.0..2.0).each { } raise a TypeError?

    Iteration needs the start object to respond to succ. A Float range is still fine for include?, cover? and case/when.
  3. 3. What does [10, 20, 30, 40][1..] return?

    An endless range as an index means 'from index 1 to the end'.
  4. 4. Which is the safe way to use an infinite range of squares?

    lazy computes values only when asked, and first(5) stops after five. The other forms loop forever or fail.
  5. 5. What is the difference between cover? and include? for "a".."z" and the value "mm"?

    cover? only compares with the ends, and "mm" sorts between them. include? on a string range checks membership in the generated sequence.

Summary

  • a..b includes b, a...b excludes it. A range stores only its ends.
  • Any comparable values can form a range. Iteration also needs succ.
  • Endless (1..) and beginless (..5) ranges are great for comparisons, slicing and clamp; endless ones need first, lazy or break when iterated.
  • step(n) and % walk a range in jumps, including float ranges.
  • cover? and === compare only with the ends, include? may check members.
  • Use (1..5).each with parentheses, and downto or reverse_each for descending order.
  • Ranges are frozen and include Enumerable.

Next: Ternary, Safe Navigation and Short-Circuit