Ranges
Prerequisites: Iterators
A range represents a sequence of values from a start to an end.
Syntax
1..5 # 1, 2, 3, 4, 5 (two dots: includes the end)
1...5 # 1, 2, 3, 4 (three dots: excludes the end)
"a".."e" # "a" through "e"
Example
p (1..5).to_a
p (1...5).to_a
p ("a".."e").to_a
p (1..10).include?(7)
p (1..10).sum
(1..3).each { |n| puts n * 10 }
Expected output
[1, 2, 3, 4, 5]
[1, 2, 3, 4]
["a", "b", "c", "d", "e"]
true
55
10
20
30
to_a turns a range into an array so you can see every value.
Ranges are also useful for checking whether a value falls between two
limits — in a case statement, or with cover? / include?:
age = 42
puts "Working age" if (18..65).cover?(age)
Working age
An endless range leaves off the end: (18..) means "18 or more".
rand(1..6) picks a random number in a range — perfect for dice.
Common mistakes
- Forgetting parentheses:
1..5.to_ameans1..(5.to_a)and fails. Write(1..5).to_a. - Mixing up
..and.... When in doubt, check withto_ainirb.