Ruby Range
Ruby范围描述了一组有起点和终点的数值。一个范围的值可以是数字、字符、字符串或对象。它是用 start_point…end_point 、 start_point…endpoint 字面符号或用 : : new 构建的 。 它为代码提供了灵活性并减少了代码的大小。
例子
# Ruby program to demonstrate
# the Range in Ruby
# Array value separator
$, =", "
# using start_point..end_point
# to_a is used to convert it
# into array
range_op = (7 .. 10).to_a
# displaying result
puts "#{range_op}"
# using start_point...end_point
# to_a is used to convert it
# into array
range_op1 = (7 ... 10).to_a
# displaying result
puts "#{range_op1}"
输出
[7, 8, 9, 10]
[7, 8, 9]
Ruby提供了以下3种类型的范围:
- 作为序列的范围
- 作为条件的范围
- 作为区间的范围
作为序列的范围
这是一种在Ruby中定义范围的一般和简单的方法,在序列中产生连续的值。它有一个开始点和一个结束点。有两个运算符用于创建范围,一个是 双点(…) 运算符,另一个是 三点(…) 运算符。
例子
# Ruby program to illustrate the ranges as sequences
#!/usr/bin/ruby
# input the value which lies between
# the range 6 and 8
ranges = 6..8
# print true if the value is lies
# between the range otherwise
# print false
puts ranges.include?(3)
# print the maximum value which lies
# between the range
ans = ranges.max
puts "Maximum value = #{ans}"
# print the minimum value which lies
# between the range
ans = ranges.min
puts "Minimum value = #{ans}"
# Iterate 3 times from 6 to 8
# and print the value
ranges.each do |digit|
puts "In Loop #{digit}"
end
输出
false
Maximum value = 8
Minimum value = 6
In Loop 6
In Loop 7
In Loop 8
作为条件的区间
范围也可以被定义为循环中的条件表达式。这里的条件被包围在开始和结束语句中。
例子
# Ruby program to illustrate the ranges as condition
#!/usr/bin/ruby
# given number
num = 4152
result = case num
when 1000..2000 then "Lies Between 1000 and 2000"
when 2000..3000 then "Lies Between 2000 and 3000"
when 4000..5000 then "Lies Between 4000 and 5000"
when 6000..7000 then "Lies Between 6000 and 7000"
else "Above 7000"
end
puts result
输出
Lies Between 4000 and 5000
作为区间的范围
范围也可以用区间来定义,以检查给定值是否在区间内。它由平等运算符(===)表示。
例如 :
# Ruby program to illustrate the ranges as intervals
#!/usr/bin/ruby
# using if statement
if (('A'..'Z') === 'D')
# display the value
puts "D lies in the range of A to Z"
# end of if
end
# using if statement
if ((1..100) === 77)
# display the value
puts "77 lies in the range of 1 to 100"
# end of if
end
输出
D lies in the range of A to Z
77 lies in the range of 1 to 100
注意: 在Ruby中,如果你试图使用反向范围操作符,那么将不会有任何返回。因为在范围操作符中,如果右边的值比左边的值小,那么它们就不会返回任何东西。为了 打印一个给定范围的反向顺序 ,总是使用范围操作符的reverse()方法。
# Ruby program to print the reverse
# order using the range operator
#!/usr/bin/ruby
# using ranges
# but it will not give any output
puts ('Z'..'W').to_a
# using reverse() method which will
# print given range in the reverse order
puts ('W'..'Z').to_a.reverse
输出
Z
Y
X
W