国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 學院 > 開發設計 > 正文

ruby 流程控制 方法

2019-10-26 19:18:51
字體:
來源:轉載
供稿:網友
這章我們將討論更多的Ruby流程控制.

case

我們用case語句測試有次序的條件.正如我們所見的,這和C,Java的switch相當接近,但更強大.

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之間的一個范圍.下面的表達式測試 i 是否在范圍內:

(2..5) === i 


case 內部也是用關系運算符 === 來同時測試幾個條件.為了保持ruby的面對對象性質, === 可以合適地理解為出現在 when 條件里的對

象.比如,下面的代碼現在第一個 when 里測試字符串是否相等,并在第二個 when 里進行正則表達式匹配.

ruby> case 'abcdef'
    | when 'aaa', 'bbb'
    |   print "aaa or bbb/n"
    | when /def/
    |   print "includes /def//n"
    | end
includes /def/
   nil 


while

雖然你將會在下一章發現并不需要經常將循環體寫得很清楚,但 Ruby 還是提供了一套構建循環的好用的方法.

while 是重復的 if.我們在猜詞游戲和正則表達式中使用過它(見前面的章節);這里,當條件(condition)為真的時候,它圍繞一個代碼域以

while condition...end的形式循環.但 while 和 if 可以很容易就運用于單獨語句:

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 


有時候你想要否定一個測試條件. unless 是 if 的否定, until 是一個否定的 while.在這里我把它們留給你實驗.

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, 
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 长泰县| 大田县| 城口县| 永清县| 溧阳市| 高阳县| 锡林浩特市| 乐业县| 会理县| 江都市| 岫岩| 从化市| 开原市| 长阳| 遂川县| 奉节县| 泸定县| 广南县| 夹江县| 巴中市| 平南县| 南康市| 黑龙江省| 杭锦后旗| 息烽县| 密云县| 梁山县| 长泰县| 广昌县| 阿勒泰市| 琼海市| 山东省| 游戏| 五常市| 木里| 恩施市| 临洮县| 贵定县| 嘉荫县| 广饶县| 邻水|