Menu
Coddy logo textTech

What is a Range?

Part of the Logic & Flow section of Coddy's Ruby journey — lesson 6 of 56.

You've already used ranges with for loops and array slicing. But a range is a real Ruby object, not just syntax, it has its own methods.

Create one with .. (two dots, inclusive) or ... (three dots, exclusive of the end value):

inclusive = 1..5    # 1, 2, 3, 4, 5
exclusive = 1...5   # 1, 2, 3, 4

Convert a range to an array with to_a to see exactly what it covers:

puts (1..5).to_a.inspect    # [1, 2, 3, 4, 5]
puts (1...5).to_a.inspect   # [1, 2, 3, 4]

Ranges aren't only for numbers. They work with anything that has an order, including letters:

puts ("a".."e").to_a.inspect  # ["a", "b", "c", "d", "e"]
challenge icon

Challenge

Beginner

Read two integers (two lines of input): a start and an end_value. Print three lines:

  1. The inclusive range start..end_value as an array (use inspect)
  2. The exclusive range start...end_value as an array
  3. The size of the inclusive range

For input 1 then 5, the output is:

[1, 2, 3, 4, 5]
[1, 2, 3, 4]
5

Cheat sheet

Ranges in Ruby use .. (inclusive) or ... (exclusive of end):

inclusive = 1..5    # 1, 2, 3, 4, 5
exclusive = 1...5   # 1, 2, 3, 4

Convert a range to an array with to_a:

puts (1..5).to_a.inspect    # [1, 2, 3, 4, 5]
puts (1...5).to_a.inspect   # [1, 2, 3, 4]

Ranges also work with letters:

puts ("a".."e").to_a.inspect  # ["a", "b", "c", "d", "e"]

Try it yourself

start     = gets.to_i
end_value = gets.to_i

# TODO: print the inclusive range, exclusive range, and inclusive size
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow