不幸的是,Ruby有点不同。PS:对此我的记忆有些模糊,如果我错了,我深表歉意
它具有break / next而不是break / continue,它们在循环方面的表现相同
循环(像其他所有循环一样)是表达式,并“返回”它们所做的最后一件事。大多数时候,从循环中获取返回值是没有意义的,因此每个人都这样做
a = 5
while a < 10
a + 1
end
但是,您可以这样做
a = 5
b = while a < 10
a + 1
end # b is now 10
但是,许多红宝石代码都通过使用块来“模拟”循环。典型的例子是
10.times do |x|
puts x
end
人们通常希望以块的结果来做事,这就是混乱的地方。break / next在块的上下文中意味着不同的事物。
中断将跳出调用该块的代码
接下来,将跳过该块中的其余代码,并将您指定的内容“返回”给该块的调用者。没有示例,这毫无意义。
def timesten
10.times{ |t| puts yield t }
end
timesten do |x|
x * 2
end
# will print
2
4
6
8 ... and so on
timesten do |x|
break
x * 2
end
# won't print anything. The break jumps out of the timesten function entirely, and the call to `puts` inside it gets skipped
timesten do |x|
break 5
x * 2
end
# This is the same as above. it's "returning" 5, but nobody is catching it. If you did a = timesten... then a would get assigned to 5
timesten do |x|
next 5
x * 2
end
# this would print
5
5
5 ... and so on, because 'next 5' skips the 'x * 2' and 'returns' 5.
嗯是的。Ruby很棒,但是它有一些糟糕的情况。这是我多年来使用它的第二糟糕的表现:-)