Ranges
Prerequisites: Loops
A range is a sequence of values defined by its two ends. It works with numbers, characters, and anything comparable that has a "next".
def r = 1..5
println r
println r.size()
println r.contains(3)
println r.from + ' to ' + r.to
println (1..<5) // exclusive end
println (1<..5) // exclusive start (Groovy 4+)
println (5..1) // counting down
println (('a'..'e').join())
println ((1..10).step(3))
1..5
5
true
1 to 5
1..<5
1<..5
5..1
abcde
[1, 4, 7, 10]
a..bincludes both ends;a..<bexcludes the end.- Reversed ranges count down.
- A range of integers is a
List, so list methods work on it.
Ranges in practice
def scores = [55, 67, 89, 91, 42, 78]
println scores[1..3] // slice a list
println scores.findAll { it in 70..100 } // range as a test
def age = 15
if (age in 13..19) println 'teenager'
println (('A'..'Z')[0..4])
println ((1..5).collect { it * it })
println ((1..100).sum())
[67, 89, 91]
[89, 91, 78]
teenager
[A, B, C, D, E]
[1, 4, 9, 16, 25]
5050
Ranges are lazy: 1..1_000_000 stores only its two ends, not a
million numbers.