范围是符号为“ ..”和“ ...”的运算符,具有起点和终点。您可以分别将它们称为双点和三点运算符。两种运算符之间的区别在于,双点运算符是包含范围的运算符,三点运算符是唯一范围的运算符,这意味着如果您打印(1..4),它将打印从1到4的数字,而如果您打印( 1…4),它将打印从1到3的数字。范围用于减小代码大小并增加Ruby代码的灵活性。
您在Ruby中获得三种类型的Ranges:
范围作为序列
间隔范围
条件范围
现在,让我们通过示例进行讨论,以更好地理解该概念。
当您将范围用作序列时,您尝试获取特定序列中的连续值。您应该以整数和端点的形式指定起点。您可以根据代码要求使用双点运算符和三点运算符。
让我们借助以下示例了解其实现:
=begin Ruby program to demonstrate ranges as sequences using .. operator. =end myrange = 4..8 maxv = myrange.max puts "Maximum value from range = #{maxv}" minv = myrange.min puts "Minimum value from range = #{minv}" if myrange.include?(8) then puts "8 is present" end myrange.each do |digit| puts "#{digit} * #{digit} = #{digit*digit}" end
输出结果
Maximum value from range = 8 Minimum value from range = 4 8 is present 4 * 4 = 16 5 * 5 = 25 6 * 6 = 36 7 * 7 = 49 8 * 8 = 64
在上面的代码中,首先我们打印的最大值和最小值超出范围,然后我们检查特定元素的存在。最后,我们将打印范围的所有元素。
现在,让我们借助三点运算符“ ...”查看相同的示例。
=begin Ruby program to demonstrate ranges as sequences using ... operator. =end myrange = 4...8 maxv = myrange.max puts "Maximum value from range = #{maxv}" minv = myrange.min puts "Minimum value from range = #{minv}" if myrange.include?(8) then puts "8 is present" else puts "8 is not present" end myrange.each do |digit| puts "#{digit} * #{digit} = #{digit*digit}" end
输出结果
Maximum value from range = 7 Minimum value from range = 4 8 is not present 4 * 4 = 16 5 * 5 = 25 6 * 6 = 36 7 * 7 = 49
现在,您可以看到当我们使用三点运算符时,它不在范围内。
您还可以将range用作循环内的条件语句。我们经常将其与for循环配合使用。请参考以下示例:
=begin Ruby program to demonstrate ranges as conditions using ... operator. =end puts "Enter start point:-" start = gets.chomp.to_i puts "Enter end point:-" endpoint = gets.chomp.to_i puts "--------------" for i in start..endpoint puts i*10 end
输出结果
Enter start point:- 10 Enter end point:- 20 -------------- 100 110 120 130 140 150 160 170 180 190 200
您还可以在switch case语句中将范围实现为条件。请参阅以下示例:
=begin Ruby program to demonstrate ranges as conditions using .. operator. =end puts "Enter the number" num = gets.chomp.to_i rslt = case num when 1000..2000 then "Between 1000 and 2000" when 2000..3000 then "Between 2000 and 3000" when 4000..5000 then "Between 4000 and 5000" when 6000..7000 then "Between 6000 and 7000" else "Above 7000" end puts rslt
输出结果
Enter the number 1200 Between 1000 and 2000
您可以观察到,当用户输入1200时,由于1200位于1000和2000之间,因此它会打印“介于1000和2000之间”。
您还可以使用范围检查范围中数字的存在。在这种情况下,我们使用“ ===”运算符。请参见以下代码:
=begin Ruby program to demonstrate ranges as intervals using .. operator. =end puts "Enter the Alphabet" alpha = gets.chomp if (('A'..'T') === alpha) puts "#{alpha} lies in the range of A to T" else puts "#{alpha} does not lies in the range of A to T" end
输出结果
RUN 1: Enter the Alphabet V V does not lies in the range of A to T RUN 2: Enter the Alphabet F F lies in the range of A to T
您可以在上面的代码中观察到我们正在使用===运算符将范围实现为间隔。