1
3
.times {
print
"
X
"
}
2 1 .upto( 5 ) { | i | print i, " " }
3 99 .downto( 95 ) { | i | print i, " " }
4 50 .step( 80 , 5 ) { | i | print i, " " }
5
6 produces:
7 X X X 1 2 3 4 5 99 98 97 96 95 50 55 60 65 70 75 80
2 1 .upto( 5 ) { | i | print i, " " }
3 99 .downto( 95 ) { | i | print i, " " }
4 50 .step( 80 , 5 ) { | i | print i, " " }
5
6 produces:
7 X X X 1 2 3 4 5 99 98 97 96 95 50 55 60 65 70 75 80
In Ruby, these sequences are created using the . . and . . . range operators. The two-dot form creates an inclusive range, and the three-dot form creates a range that excludes the specified high value.
A final use of the versatile range is as an interval test: seeing whether some value falls within the interval represented by the range.
1
(
1
..
10
)
===
5
#
=> true
2 ( 1 .. 10 ) === 15 # => false
3 ( 1 .. 10 ) === 3.14159 # => true
4 ( ' a ' .. ' j ' ) === ' c ' # => true
5 ( ' a ' .. ' j ' ) === ' z ' # => false
2 ( 1 .. 10 ) === 15 # => false
3 ( 1 .. 10 ) === 3.14159 # => true
4 ( ' a ' .. ' j ' ) === ' c ' # => true
5 ( ' a ' .. ' j ' ) === ' z ' # => false