Ruby Range
Ranges are ubiquitous: from a to z, 0 to 9, and so on. Ruby supports ranges and allows us to use them in various ways:
- Ranges as sequences
- Ranges as conditions
- Ranges as intervals
Ranges as Sequences
The first and most common use of ranges is to express sequences. Sequences have a start, an end, and a way to produce successive values in the sequence.
Ruby uses ..
and ...
range operators to create these sequences. The two-dot form creates an inclusive range, while the three-dot form creates a range that excludes the specified high value.
(1..5) #==> 1, 2, 3, 4, 5
(1...5) #==> 1, 2, 3, 4
('a'..'d') #==> 'a', 'b', 'c', 'd'
The sequence 1..100 is a Range
object that includes references to two Fixnum
objects. If needed, you can convert the range to a list using the to_a
method. Try the following example:
Example
#!/usr/bin/ruby
$, =", " # Array value separator
range1 = (1..10).to_a
range2 = ('bar'..'bat').to_a
puts "#{range1}"
puts "#{range2}"
The output of the above example is:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["bar", "bas", "bat"]
Ranges implement methods that allow you to iterate over them, and you can check their content in various ways:
Example
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
# Specify range
digits = 0..9
puts digits.include?(5)
ret = digits.min
puts "最小值为 #{ret}"
ret = digits.max
puts "最大值为 #{ret}"
ret = digits.reject {|i| i < 5 }
puts "不符合条件的有 #{ret}"
digits.each do |digit|
puts "在循环中 #{digit}"
end
The output of the above example is:
true
最小值为 0
最大值为 9
不符合条件的有 [5, 6, 7, 8, 9]
在循环中 0
在循环中 1
在循环中 2
在循环中 3
在循环中 4
在循环中 5
在循环中 6
在循环中 7
在循环中 8
在循环中 9
Ranges as Conditions
Ranges can also be used as conditional expressions. For example, the following code snippet prints lines from standard input where each set starts with the word start and ends with the word end:
while gets
print if /start/../end/
end
Ranges can be used in case
statements:
Example
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
score = 70
result = case score
when 0..40
"糟糕的分数"
when 41..60
"快要及格"
when 61..70
"及格分数"
when 71..100
"良好分数"
else
"错误的分数"
end
puts result
The output of the above example is:
及格分数
Ranges as Intervals
The last use of ranges is interval testing: checking whether a specified value falls within the specified range. This is done using the ===
equality operator.
Example
#!/usr/bin/ruby
# -*- coding: UTF-8 -*-
if ((1..10) === 5)
puts "5 在 (1..10)"
end
if (('a'..'j') === 'c')
puts "c 在 ('a'..'j')"
end
if (('a'..'j') === 'z')
puts "z 在 ('a'..'j')"
end
The output of the above example is:
5 在 (1..10)
c 在 ('a'..'j')