Ranges
Two and three dots
Two dots build a range that includes its end, while three dots build one that excludes it. Ranges also cover strings in order, such as letters from a to c. Small ranges expand into arrays with to_a for a quick look.
puts (1..5).to_a.length puts (1...5).to_a.length puts ("a".."c").to_a.length
ruby dots.rb
5
4
3
Include checks
The predicate include? reports whether a value sits inside the range. The predicate cover? answers the same question with a single comparison, which runs faster on very large ranges.
r = (1..5) puts r.include?(3) puts r.include?(9) puts r.cover?(3)
ruby cover.rb
true
false
true
Loop over ranges
Ranges respond to each just like arrays, yielding every value in turn. The method step moves by more than one, which is handy for skipping ahead. Call to_a when an actual array is needed downstream.
(1..3).each do |n| puts n end puts (1..10).step(3).to_a.length
ruby step.rb
1
2
3
4
The stepped range holds 1, 4, 7, and 10, so its length is 4.
Ranges in case
A when branch compares with triple equals, so a range matches any value inside it. Number bands, such as school grades, read naturally this way. The first matching branch wins, with else as the fallback.
score = 85 result = case score when 90..100 "top" when 75..89 "good" else "rest" end puts result
ruby grade.rb
good
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
How many dots include the end of a range?
Answer
Two:
1..5includes 5Two dots make an inclusive range and three dots exclude the end.
-
What does this program print?
puts (1..5).to_a.length puts (1...5).to_a.lengthAnswer
5 / 4
The inclusive range holds five values, the exclusive one four.
-
What does this program print?
puts ("a".."c").to_a.lengthAnswer
3
A string range counts in order from a to c, which is three letters.
-
What does
r.include?(9)return forr = (1..5)?Answer
false
9 is outside the range, so the predicate is false.
-
How does
cover?differ frominclude??Answer
It answers with a single comparison, which is fast on a large range
include? walks the values, while cover? compares the bounds.
-
What does this program print?
(1..3).each { |n| puts n }Answer
1 / 2 / 3
each yields every value of the range in order.
-
What does
(1..10).step(3).to_acontain?Answer
[1, 4, 7, 10]
step starts at 1 and moves by 3, stopping at the last value that fits.
-
What does this program print?
score = 85 result = case score when 90..100 "top" when 75..89 "good" else "rest" end puts resultAnswer
good
85 falls in 75..89, and the first matching when wins.
-
Which comparison makes a range match in a when?
Answer
===
Range#=== asks whether the value is covered by the range.
-
When is
to_aneeded on a range?Answer
When the code downstream needs a real array
A range is lazy about its values, and to_a materialises them when an array is required.
Article author: Arthur Isaev