Ruby Ranges
A range is a span of values from a start value to an end value. The values sit in order between the start and the end.
A range that includes its end
Two dots make a range. The end value 5 is part of this range.
p (1..5).to_aA range that leaves its end out
Three dots make a range. The end value 5 is not part of this range.
p (1...5).to_aA range in a case test
A when line can hold a range. The test passes when the value sits inside the range.
score = 85
case score
when 90..100
puts "Top score"
when 80..89
puts "Good score"
else
puts "Keep trying"
endExample
p (1..4).to_a
p (1...4).to_a
score = 73
case score
when 90..100
puts "Top score"
when 70..89
puts "Passing score"
else
puts "Try again"
endKey points
- A range writes its start, dots, and its end.
- Two dots include the end value in the range.
- Three dots leave the end value out of the range.
- Use to_a to see every value in a range in one line.
- A range can stand in a when line to test a span of values.
In this example, the first line prints the values of 1..4 with the end value in the list. The second line prints the values of 1...4 with the end value left out. The score is 73, so the test moves past the first range. The value 73 sits inside 70..89, so the program prints Passing score.
Note
A p line shows the values from to_a as one list in square brackets.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Ruby Compiler
Exercise
What does (1...5).to_a give?