Ruby - 範圍



範圍無處不在:1月到12月,0到9,50到67行,等等。Ruby 支援範圍,並允許我們以各種方式使用範圍。

  • 範圍作為序列
  • 範圍作為條件
  • 範圍作為區間

範圍作為序列

範圍的第一個,也許是最自然的用途是表達一個序列。序列具有起始點、結束點和生成序列中連續值的方法。

Ruby 使用“..”“...”範圍運算子建立這些序列。雙點形式建立一個包含範圍,而三點形式建立一個排除指定高值的範圍。

(1..5)        #==> 1, 2, 3, 4, 5
(1...5)       #==> 1, 2, 3, 4
('a'..'d')    #==> 'a', 'b', 'c', 'd'

序列 1..100 保持為包含對兩個Fixnum物件的引用的 Range 物件。如果需要,可以使用to_a方法將範圍轉換為列表。嘗試以下示例:

#!/usr/bin/ruby

$, =", "   # Array value separator
range1 = (1..10).to_a
range2 = ('bar'..'bat').to_a

puts "#{range1}"
puts "#{range2}"

這將產生以下結果:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
["bar", "bas", "bat"]

範圍實現了允許您以各種方式迭代它們並測試其內容的方法:

#!/usr/bin/ruby

# Assume a range
digits = 0..9

puts digits.include?(5)
ret = digits.min
puts "Min value is #{ret}"

ret = digits.max
puts "Max value is #{ret}"

ret = digits.reject {|i| i < 5 }
puts "Rejected values are #{ret}"

digits.each do |digit|
   puts "In Loop #{digit}"
end

這將產生以下結果:

true
Min value is 0
Max value is 9
Rejected values are 5, 6, 7, 8, 9
In Loop 0
In Loop 1
In Loop 2
In Loop 3
In Loop 4
In Loop 5
In Loop 6
In Loop 7
In Loop 8
In Loop 9

範圍作為條件

範圍也可以用作條件表示式。例如,以下程式碼片段列印來自標準輸入的線集,其中每個線集的第一行包含單詞start,最後一行包含單詞ends

while gets
   print if /start/../end/
end

範圍可以用在 case 語句中:

#!/usr/bin/ruby

score = 70

result = case score
   when 0..40 then "Fail"
   when 41..60 then "Pass"
   when 61..70 then "Pass with Merit"
   when 71..100 then "Pass with Distinction"
   else "Invalid Score"
end

puts result

這將產生以下結果:

Pass with Merit

範圍作為區間

多功能範圍的最終用途是作為區間測試:檢視某個值是否落在範圍表示的區間內。這是使用 ===(case 等式運算子)完成的。

#!/usr/bin/ruby

if ((1..10) === 5)
   puts "5 lies in (1..10)"
end

if (('a'..'j') === 'c')
   puts "c lies in ('a'..'j')"
end

if (('a'..'j') === 'z')
   puts "z lies in ('a'..'j')"
end

這將產生以下結果:

5 lies in (1..10)
c lies in ('a'..'j')
廣告
© . All rights reserved.