Ruby-流程控制

来自站长百科
跳转至: 导航、​ 搜索

导航: 上一页 | ASP | PHP | JSP | HTML | CSS | XHTML | aJAX | Ruby | JAVA | XML | Python | ColdFusion

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,

next, and redo:

有四种从内部中断循环的方法.第一,和C一样break从循环中完全退出.第二, next 跳到下一次循环迭代的开始(对应于C的 continue ).第

三,Ruby有redo,它可以重新开始现在的迭代.下面是用 C 代码对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:
...


第四种方法是由循环内跳出的方法是 returen. return的结果是不仅从循环中跳出,而且会从含循环的方法中跳出.如果有参数,它会返回给方法调用,不然就返回nil.


for[ ]

C程序员现在会想知道怎样做一个"for"循环.Ruby的for比你想象的要有趣一点.下面的loop由集合中的元素控制运行:

for elt in collection  
...
end


集合可以是一个数集(也是传统意义上的for循环):

ruby> for num in (4..6)
| print num,"\n"
| end
4
5
6
4..6


也可以是其它的什么类型的集合,比如一个数组:

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"]


但我们说过头了.for其实是 each 的另一写法,正巧,这是我们关于迭代器的第一个例子.下面的两种形式是等价的:

#  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|
...
}


一旦你熟悉了迭代器,它便会常常代替传统的循环.它们一般更容易处理.因此,让我们接着学习更多关于迭代器的知识.