這章我們將討論更多的Ruby流程控制.
case
我們用case語(yǔ)句測(cè)試有次序的條件.正如我們所見(jiàn)的,這和C,Java的switch相當(dāng)接近,但更強(qiáng)大.
ruby> i=8
ruby> case i
| when 1, 2..5
| print "1..5/n"
| when 6..10
| print "6..10/n"
| end
6..10
nil
2..5表示2到5之間的一個(gè)范圍.下面的表達(dá)式測(cè)試 i 是否在范圍內(nèi):
(2..5) === i
case 內(nèi)部也是用關(guān)系運(yùn)算符 === 來(lái)同時(shí)測(cè)試幾個(gè)條件.為了保持ruby的面對(duì)對(duì)象性質(zhì), === 可以合適地理解為出現(xiàn)在 when 條件里的對(duì)
象.比如,下面的代碼現(xiàn)在第一個(gè) when 里測(cè)試字符串是否相等,并在第二個(gè) when 里進(jìn)行正則表達(dá)式匹配.
ruby> case 'abcdef'
| when 'aaa', 'bbb'
| print "aaa or bbb/n"
| when /def/
| print "includes /def//n"
| end
includes /def/
nil
while
雖然你將會(huì)在下一章發(fā)現(xiàn)并不需要經(jīng)常將循環(huán)體寫(xiě)得很清楚,但 Ruby 還是提供了一套構(gòu)建循環(huán)的好用的方法.
while 是重復(fù)的 if.我們?cè)诓略~游戲和正則表達(dá)式中使用過(guò)它(見(jiàn)前面的章節(jié));這里,當(dāng)條件(condition)為真的時(shí)候,它圍繞一個(gè)代碼域以
while condition...end的形式循環(huán).但 while 和 if 可以很容易就運(yùn)用于單獨(dú)語(yǔ)句:
ruby> i = 0
0
ruby> print "It's zero./n" if i==0
It's zero.
nil
ruby> print "It's negative./n" if i<0
nil
ruby> print "#{i+=1}/n" while i<3
1
2
3
nil
有時(shí)候你想要否定一個(gè)測(cè)試條件. unless 是 if 的否定, until 是一個(gè)否定的 while.在這里我把它們留給你實(shí)驗(yàn).
There are four ways to interrupt the progress of a loop from inside. First, break means, as in C, to escape from the
loop entirely. Second, next skips to the beginning of the next iteration of the loop (corresponding to C's continue).
Third, ruby has redo, which restarts the current iteration. The following is C code illustrating the meanings of break,
next, and redo:
有四種從內(nèi)部中斷循環(huán)的方法.第一,和C一樣break從循環(huán)中完全退出.第二, next 跳到下一次循環(huán)迭代的開(kāi)始(對(duì)應(yīng)于C的 continue ).第
三,Ruby有redo,它可以重新開(kāi)始現(xiàn)在的迭代.下面是用 C 代碼對(duì)break,next,redo的意義做了演示:
while (condition) {
label_redo:
goto label_next; /* ruby's "next" */
goto label_break; /* ruby's "break" */
goto label_redo; /* ruby's "redo" */
...
...
label_next:
}
label_break:
...
第四種方法是由循環(huán)內(nèi)跳出的方法是 returen. return的結(jié)果是不僅從循環(huán)中跳出,而且會(huì)從含循環(huán)的方法中跳出.如果有參數(shù),它會(huì)返回給方法調(diào)用,不然就返回nil.
for
C程序員現(xiàn)在會(huì)想知道怎樣做一個(gè)"for"循環(huán).Ruby的for比你想象的要有趣一點(diǎn).下面的loop由集合中的元素控制運(yùn)行:
for elt in collection
...
end
集合可以是一個(gè)數(shù)集(也是傳統(tǒng)意義上的for循環(huán)):
ruby> for num in (4..6)
| print num,"/n"
| end
4
5
6
4..6
也可以是其它的什么類型的集合,比如一個(gè)數(shù)組:
ruby> for elt in [100,-9.6,"pickle"]
| print "#{elt}/t(#{elt.type})/n"
| end
100 (Fixnum)
-9.6 (Float)
pickle (String)
[100, -9.6, "pickle"]
但我們說(shuō)過(guò)頭了.for其實(shí)是 each 的另一寫(xiě)法,正巧,這是我們關(guān)于迭代器的第一個(gè)例子.下面的兩種形式是等價(jià)的:
# If you're used to C or Java, you might prefer this.
for i in collection
...
end
# A Smalltalk programmer might prefer this.
collection.each {|i|
...
}
一旦你熟悉了迭代器,它便會(huì)常常代替?zhèn)鹘y(tǒng)的循環(huán).它們一般更容易處理.因此,讓我們接著學(xué)習(xí)更多關(guān)于迭代器的知識(shí).