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

Ranges

In this page:

  1. Ranges

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}" }
🔒

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.