rubyonrails:ruby 流程控制 思路方法

这章我们将讨论更多Ruby流程控制.

我们用语句测试有次序条件.正如我们所见,这和C,Javaswitch相当接近,但更强大.
ruby> i=8
ruby> i
| when 1, 2..5
| pr "1..5\n"
| when 6..10
| pr "6..10\n"
| end
6..10
nil

2..5表示2到5的间个范围.下面表达式测试 i 是否在范围内:
(2..5) = i

内部也是用关系运算符 = 来同时测试几个条件.为了保持ruby面对对象性质, = 可以合适地理解为出现在 when 条件里
象.比如,下面代码现在第个 when 里测试串是否相等,并在第 2个 when 里进行正则表达式匹配.
ruby> 'abcdef'
| when 'aaa', 'bbb'
| pr "aaa or bbb\n"
| when /def/
| pr "s /def/\n"
| end
s /def/
nil

while
虽然你将会在下章发现并不需要经常将循环体写得很清楚,但 Ruby 还是提供了套构建循环好用思路方法.
while 是重复 .我们在猜词游戏和正则表达式中使用过它(见前面章节);这里,当条件(condition)为真时候,它围绕个代码域以
while condition...end形式循环.但 while 和 可以很容易就运用于单独语句:
ruby> i = 0
0
ruby> pr "It's zero.\n" i0
It's zero.
nil
ruby> pr "It's negative.\n" i<0
nil
ruby> pr "#{i1}\n" while i<3
1
2
3
nil

有时候你想要否定个测试条件. unless 是 否定, until 是个否定 while.在这里我把它们留给你实验.
There are four ways to errupt the progress of a loop from inside. First, 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 ,
next, and redo:
有 4种从内部中断循环思路方法.第,和C从循环中完全退出.第 2, next 跳到下次循环迭代开始(对应于C continue ).第
3,Ruby有redo,它可以重新开始现在迭代.下面是用 C 代码对,next,redo意义做了演示:
while (condition) {
label_redo:
goto label_next; /* ruby's "next" */
goto label_; /* ruby's "" */
goto label_redo; /* ruby's "redo" */
...
...
label_next:
}
label_:
...

第 4种思路方法是由循环内跳出思路方法是 returen. 结果是不仅从循环中跳出,而且会从含循环思路方法中跳出.如果有参数,它会返回给思路方法,不然就返回nil.
for
C员现在会想知道怎样做个"for"循环.Rubyfor比你想象要有趣点.下面loop由集合中元素控制运行:
for elt in collection
...
end

集合可以是个数集(也是传统意义上for循环):
ruby> for num in (4..6)
| pr num,"\n"
| end
4
5
6
4..6

也可以是其它什么类型集合,比如:
ruby> for elt in [100,-9.6,"pickle"]
| pr "#{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|
...
}

旦你熟悉了迭代器,它便会常常代替传统循环.它们般更容易处理.因此,让我们接着学习更多有关迭代器知识.
Tags:  ruby是什么 ruby教程 ruby是什么意思 rubyonrails

延伸阅读

最新评论

发表评论