Lesson 8 of 15

Ranges

Ranges in Ruby

A range represents a sequence of values between two endpoints:

(1..5)    # inclusive: 1, 2, 3, 4, 5
(1...5)   # exclusive: 1, 2, 3, 4  (excludes 5)
('a'..'e')  # character range: a, b, c, d, e

Two dots ... means "up to but not including" the end.

Common Operations

r = (1..5)
puts r.include?(3)       # true
puts r.to_a.inspect      # [1, 2, 3, 4, 5]
puts r.min               # 1
puts r.max               # 5
puts r.sum               # 15
puts r.count             # 5

Iterating

Ranges work naturally with each:

(1..3).each { |n| puts n }
# 1
# 2
# 3

Your Task

Print four values:

  1. Length of (1..5) as an array
  2. Length of (1...5) as an array
  3. Whether 7 is in (1..10)
  4. Sum of (1..100)
ruby.wasm loading...
Loading...
Click "Run" to execute your code.