詳解Ruby中範圍的概念

來源:互聯網
上載者:User

詳解Ruby中範圍的概念

   這篇文章主要介紹了詳解Ruby中範圍的概念,需要的朋友可以參考下

  範圍無處不在:1月至12月,0至9日,50至67行,依此類推。 Ruby支援範圍,並允許我們使用多種方式的範圍:

  作為序列範圍

  作為條件範圍

  作為區間範圍

  作為序列範圍:

  首先,也許是最自然的使用範圍來表達序列。序列有一個起點,一個終點和序列中的連續值的方法來生產。

  Ruby建立'' ..''和'' ...''範圍內運算子使用這些序列。這兩個點的形式建立一個包容性的範圍,而三個點的形式建立了一個範圍,不包括指定的高值。

  ?

1

2

3

(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方法。試試下面的例子:

  ?

1

2

3

4

5

6

7

8

#!/usr/bin/ruby

 

$, =", " # Array value separator

range1 = (1..10).to_a

range2 = ('bar'..'bat').to_a

 

puts "#{range1}"

puts "#{range2}"

  這將產生以下結果:

  ?

1

2

1, 2, 3, 4, 5, 6, 7, 8, 9, 10

bar, bas, bat

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

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

#!/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

  這將產生以下結果:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

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

  作為條件的範圍:

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

  ?

1

2

3

while gets

print if /start/../end/

end

  範圍可以使用 case 語句:

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

#!/usr/bin/ruby

 

score = 70

 

result = 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"

end

 

puts result

  這將產生以下結果:

  ?

1

Pass with Merit

  區間範圍:

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

  ?

1

2

3

4

5

6

7

8

9

10

11

12

13

#!/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

  這將產生以下結果:

  ?

1

2

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.