首页 > 学院 > 开发设计 > 正文

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, 
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表