Ruby Ranges (Range)
Ranges are everywhere: a to z, 0 to 9, and so on. Ruby supports ranges and allows us to use them in different ways:
- Ranges as sequences
- Ranges as conditions
- Ranges as intervals
Ranges as sequences
The first and most common use of a range is to express a sequence. A sequence has a start point, an end point, and a way of producing successive values in the sequence.
Ruby uses the ''..'' and ''...'' range operator to create these sequences. The two-dot form creates a range that includes the specified highest value, while the three-dot form creates a range that excludes the specified highest value.
(
.5
)
==> 1, 2, 3, 4, 5
(
.
.5
)
==> 1, 2, 3, 4
(
'
a
'
..
'
d
'
)
==> 'a', 'b', 'c', 'd'
The sequence 1..100 is a Range object that contains references to two Fixnum objects. If needed, you can use the to_a method to convert a range into a list. Try the following example:
Example
!/usr/bin/ruby
$,
=
"
,
"
Array value separator
range1
=
(
.10
)
.
to_a
range2
=
(
'
bar
'
..
'
bat
'
)
.
to_a
puts
"
#{range1}
"
puts
"
#{range2}
"
Try it »
The above example produces the following output:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["bar", "bas", "bat"]
Ranges implement methods that let you iterate over them, and you can inspect their contents in several ways:
Example
!/usr/bin/ruby
-- coding: UTF-8 --
Specify the range
digits
=
.9
puts
digits
.
include
?
(
5
)
ret
=
digits
.
min
puts
"
The minimum value is #{ret}
"
ret
=
digits
.
max
puts
"
The maximum value is #{ret}
"
ret
=
digits
.
reject
{|
i
|
i
<
5
}
puts
"Those not meeting the condition are #{ret}
"
digits
.
each
do
|
digit
|
puts
"
In the loop #{digit}
"
end
Try it »
The above example produces the following output:
true
最小值为 0
最大值为 9
不符合条件的有 [5, 6, 7, 8, 9]
在循环中 0
在循环中 1
在循环中 2
在循环中 3
在循环中 4
在循环中 5
在循环中 6
在循环中 7
在循环中 8
在循环中 9
Ranges as conditions
A range can also be used as a conditional expression. For example, the following code snippet prints lines from standard input where the first line of each set contains the word start, and the last line contains the word end.:
while
gets
if
/
start
/
..
/
end
/
end
Ranges can be used in case statements:
Example
!/usr/bin/ruby
-- coding: UTF-8 --
score
=
70
result
=
case
score
when
.40
"
Poor score
"
when
.60
"
Almost passing
"
when
.70
"
Passing score
"
when
.100
"
Good score
"
else
"
Invalid score
"
end
puts
result
Try it »
The above example produces the following output:
及格分数
Ranges as intervals
The last use of a range is interval testing: checking whether a specified value falls within a given range. This is done using the === equality operator.
Example
!/usr/bin/ruby
-- coding: UTF-8 --
if
(
(
.10
)
===
5
)
puts
"
5 is in (1..10)
"
end
if
(
(
'
a
'
..
'
j
'
)
===
'
c
'
)
puts
"
c is in ('a'..'j')
"
end
if
(
(
'
a
'
..
'
j
'
)
===
'
z
'
)
puts
"
z is in ('a'..'j')
"
end
Try it »
The above example produces the following output:
5 在 (1..10)
c 在 ('a'..'j')