Ruby Ranges
Represent sequences of values efficiently
📊 What are Ruby Ranges?
Ranges represent an interval of values with a beginning and an end. They're created using two or three dots between values, providing an efficient way to work with sequences without storing every element in memory.
# Inclusive range (includes end value)
numbers = (1..5)
puts numbers.to_a.inspect # Output: [1, 2, 3, 4, 5]
# Exclusive range (excludes end value)
numbers = (1...5)
puts numbers.to_a.inspect # Output: [1, 2, 3, 4]
Output:
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
Range Concepts
Inclusive Range
Two dots include end value
(1..5)
# 1, 2, 3, 4, 5
Exclusive Range
Three dots exclude end value
(1...5)
# 1, 2, 3, 4
Letter Ranges
Works with characters too
('a'..'e')
# a, b, c, d, e
Membership Test
Check if value is in range
(1..10).include?(5)
# true
🔹 Creating Ranges
Ranges can be created with numbers, letters, or any comparable objects. Use two dots (..) for inclusive ranges that include the end value, or three dots (...) for exclusive ranges that stop before the end value. Ranges are memory-efficient because they don't store all values.
# Inclusive range with numbers
inclusive = (1..10)
puts inclusive.to_a.inspect # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Exclusive range with numbers
exclusive = (1...10)
puts exclusive.to_a.inspect # Output: [1, 2, 3, 4, 5, 6, 7, 8, 9]
# Range with letters
letters = ('a'..'f')
puts letters.to_a.inspect # Output: ["a", "b", "c", "d", "e", "f"]
# Negative numbers
negative = (-5..-1)
puts negative.to_a.inspect # Output: [-5, -4, -3, -2, -1]
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
["a", "b", "c", "d", "e", "f"]
[-5, -4, -3, -2, -1]
🔹 Using Ranges in Loops
Ranges are commonly used in loops to iterate over a sequence of values. They work seamlessly with each, for, and other iteration methods. This makes ranges perfect for counting, generating sequences, or repeating actions a specific number of times.
# Using range with each
(1..5).each do |num|
puts "Number: #{num}"
end
# Using range in for loop
for i in (1..3)
puts "Iteration #{i}"
end
# Using range with times alternative
(1..4).each do |n|
puts "Step #{n}"
end
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
🔹 Range Methods
Ranges come with useful methods for checking membership, getting boundaries, and converting to arrays. The include? method tests if a value exists in the range, while first and last return the boundary values. These methods make ranges versatile for various programming tasks.
range = (10..20)
# Check if value is in range
puts range.include?(15) # Output: true
puts range.include?(25) # Output: false
# Get first and last values
puts range.first # Output: 10
puts range.last # Output: 20
# Get size
puts range.size # Output: 11
# Check if range covers another value
puts range.cover?(15) # Output: true
# Convert to array
puts range.to_a.inspect # Output: [10, 11, 12, ..., 20]
Output:
true
false
10
20
11
true
🔹 Ranges as Conditions
Ranges can be used in case statements and conditional expressions to check if a value falls within a specific interval. This makes code more readable and concise when dealing with value ranges, such as age groups, scores, or categories.
score = 85
# Using range in case statement
grade = case score
when 90..100
"A"
when 80..89
"B"
when 70..79
"C"
when 60..69
"D"
else
"F"
end
puts "Grade: #{grade}" # Output: Grade: B
# Using range in if statement
age = 25
if (18..65).include?(age)
puts "Working age" # Output: Working age
end
Output:
Grade: B
Working age
🔹 Practical Range Examples
Ranges are useful in many real-world scenarios like array slicing, generating sequences, and filtering data. They provide a clean syntax for working with consecutive values and can make your code more expressive and easier to understand.
# Array slicing with ranges
numbers = [10, 20, 30, 40, 50, 60]
puts numbers[1..3].inspect # Output: [20, 30, 40]
puts numbers[2...5].inspect # Output: [30, 40, 50]
# Generate alphabet
alphabet = ('a'..'z').to_a
puts alphabet[0..4].inspect # Output: ["a", "b", "c", "d", "e"]
# Check age category
age = 30
category = case age
when 0..12
"Child"
when 13..19
"Teenager"
when 20..59
"Adult"
else
"Senior"
end
puts category # Output: Adult
Output:
[20, 30, 40]
[30, 40, 50]
["a", "b", "c", "d", "e"]
Adult