詳解Ruby中範圍的概念_ruby專題

來源:互聯網
上載者:User

 範圍無處不在: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作為一個Range對象包含兩個Fixnum的對象的引用。如果需要,可以將一系列的列表使用to_a方法。試試下面的例子:

#!/usr/bin/ruby$, =", "  # Array value separatorrange1 = (1..10).to_arange2 = ('bar'..'bat').to_aputs "#{range1}"puts "#{range2}"

這將產生以下結果:

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

範圍實現方法,可在它們之間迭代並在各種不同的方式測試他們的內容:

#!/usr/bin/ruby# Assume a rangedigits = 0..9puts digits.include?(5)ret = digits.minputs "Min value is #{ret}"ret = digits.maxputs "Max value is #{ret}"ret = digits.reject {|i| i < 5 }puts "Rejected values are #{ret}"digits.each do |digit|  puts "In Loop #{digit}"end

這將產生以下結果:

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

作為條件的範圍:

範圍也可以使用作為條件運算式。例如,下面的程式碼片段列印套行從標準輸入,每一組中的第一行包含單詞開始和結束的最後一行字:

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

範圍可以使用 case 語句:

#!/usr/bin/rubyscore = 70result = case score  when 0..40: "Fail"  when 41..60: "Pass"  when 61..70: "Pass with Merit"  when 71..100: "Pass with Distinction"  else "Invalid Score"endputs result

這將產生以下結果:

Pass with Merit

區間範圍:

最後一個使用的全能型的範圍是為間隔測試:是否有某個值落在該區間的時間間隔內,這是使用 === 情況下相等操作。

#!/usr/bin/rubyif ((1..10) === 5) puts "5 lies in (1..10)"endif (('a'..'j') === 'c') puts "c lies in ('a'..'j')"endif (('a'..'j') === 'z') puts "z lies in ('a'..'j')"end

這將產生以下結果:

5 lies in (1..10)c lies in ('a'..'j')

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.