Ranges
| Two and three dots | |
| Include checks | |
| Loop over ranges | |
| Ranges in case |
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
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)
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
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
good
Next: Methods
Article author: Arthur Isaev