← Back to Ruby Course | Chapter 4: Arrays | Lesson 7 of 7

Ranges

A range is a shortcut for a run of values, like one to five without writing them all. Two dots include the last number and three dots leave it out.

In this page:

  1. Ranges
Syntax
ruby
inclusive = (start..finish)
exclusive = (start...finish)
range.to_a
range.include?(value)

Ranges

A range, written as 1..5 (inclusive) or 1...5 (exclusive of the end), represents a sequence of values and can be converted to an array with .to_a.

Ranges are commonly used for iteration ((1..5).each) and for slicing arrays or strings. They're lazily evaluated, so (1..Float::INFINITY) doesn't try to build an infinite array right away.

Warning: 1...5 (three dots) excludes the final value, while 1..5 (two dots) includes it -- easy to confuse at a glance.

Example: Ranges

markup
inclusive = (1..5).to_a
exclusive = (1...5).to_a

puts inclusive.inspect
puts exclusive.inspect

(1..3).each { |n| puts "Number: #{n}" }
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
Common Mistakes
  1. Using 1..5 and expecting the last number to be excluded, when .. includes it and ... excludes it.
  2. Calling (5..1).to_a and expecting [5, 4, 3, 2, 1], when a backward range is empty; use 5.downto(1).
  3. Writing 1..5.each without parentheses, which calls each on 5; write (1..5).each.
Chapter Summary
  • Arrays are created and changed with methods such as push, pop, shift, and unshift.
  • each, map, select, and reject iterate and transform elements.
  • flatten, zip, other array methods, and ranges help work with collections.
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.