📜  红宝石 |范围

📅  最后修改于: 2022-05-13 01:54:48.027000             🧑  作者: Mango

红宝石 |范围

先决条件:Ruby 范围运算符

Ruby 范围描述了一组具有开始和结束的值。范围的值可以是数字、字符、字符串或对象。它是使用start_point..end_pointstart_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 种类型的范围,如下所示:

  1. 范围作为序列
  2. 范围作为条件
  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

范围作为条件

范围也可以定义为循环中的条件表达式。这里的条件包含在 start 和 end 语句中。

例子:

# 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