APPENDIX B: Introduction to Groovy 413
Listing B-20. Creating and Using Ranges
- def numRange = 0..9
- numRange.each {print it}
- println ""
- println numRange.contains(5)
- def reverseRange = 9..0
- reverseRange.each {print it}
- def exclusiveRange = 1..<10
- println ""
- exclusiveRange.each {print it}
- def alphabet = 'a'..'z'
- println ""
- println alphabet.size()
- println alphabet[25]
Lines 1, 5, 7, and 10 illustrate how to define ranges.
Line 1 defines an inclusive range of numbers.
Line 10 defines an inclusive range of lowercase letters.
Line 7 defines an exclusive list of numbers. The range results in a range of
numbers 1 to 9, excluding 10.
Line 5 creates a range in reverse order, 9 through 0. Frequently, ranges are used for
iterating. In Listing B-20, each() was used to iterate over the range. Listing B-21
shows three ways you can use a range to iterate: one in Java and two in Groovy.
0123456789
true
9876543210
123456789
26
z
Listing B-21. Iterating with Ranges
for (i in 0..9) {
println i
}
(0..9).each { i->
println i
}
The each() method is used to iterate through and apply the closure on every element.