国产探花免费观看_亚洲丰满少妇自慰呻吟_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, 
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 北宁市| 乐亭县| 郎溪县| 逊克县| 革吉县| 裕民县| 平昌县| 庆元县| 九寨沟县| 威远县| 宜章县| 水富县| 延吉市| 涿鹿县| 商城县| 维西| 磐石市| 滨州市| 崇义县| 炉霍县| 沐川县| 丰镇市| 军事| 金阳县| 通道| 潢川县| 桦川县| 越西县| 万荣县| 莆田市| 大名县| 邓州市| 两当县| 宣威市| 扶风县| 龙山县| 江阴市| 申扎县| 宿州市| 巧家县| 城市|