這章我們將討論更多的Ruby流程控制.
case
我們用case語句測試有次序的條件.正如我們所見的,這和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á)式測試 i 是否在范圍內(nèi):
(2..5) === i
case 內(nèi)部也是用關(guān)系運(yùn)算符 === 來同時(shí)測試幾個(gè)條件.為了保持ruby的面對對象性質(zhì), === 可以合適地理解為出現(xiàn)在 when 條件里的對
象.比如,下面的代碼現(xiàn)在第一個(gè) when 里測試字符串是否相等,并在第二個(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
雖然你將會在下一章發(fā)現(xiàn)并不需要經(jīng)常將循環(huán)體寫得很清楚,但 Ruby 還是提供了一套構(gòu)建循環(huán)的好用的方法.
while 是重復(fù)的 if.我們在猜詞游戲和正則表達(dá)式中使用過它(見前面的章節(jié));這里,當(dāng)條件(condition)為真的時(shí)候,它圍繞一個(gè)代碼域以
while condition...end的形式循環(huán).但 while 和 if 可以很容易就運(yùn)用于單獨(dú)語句:
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è)測試條件. 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,