Ruby:for 循环和each 循环有什么区别?
可能的重复:
Ruby 中的 for 与 every
假设我们有一个数组,例如
sites = %w[stackoverflow stackexchange serverfault]
之间有什么区别
for x in sites do
puts x
end
和
sites.each do |x|
puts x
end
?
对我来说,它们似乎做了同样的事情,并且 for
循环的语法对我来说更清晰。有区别吗?在什么情况下这会是一个大问题?
Possible Duplicate:
for vs each in Ruby
Let's say that we have an array, like
sites = %w[stackoverflow stackexchange serverfault]
What's the difference between
for x in sites do
puts x
end
and
sites.each do |x|
puts x
end
?
They seem to do the same exact thing, to me, and the syntax of the for
loop is clearer to me. Is there a difference? In what situations would this be a big deal?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
关于作用域有一个微妙的差异,但我建议充分理解它,因为它揭示了 Ruby 的一些重要方面。
for
是一个语法结构,有点类似于if
。无论您在for
块中定义什么,都将在for
之后保持定义:另一方面,
each
是一个方法 接收一个块。 Block 引入了新的词法作用域,因此无论您在其中引入什么变量,在方法完成后都不会存在:我建议完全忘记
for
,因为使用each
是惯用的在 Ruby 中用于遍历枚举。它还通过减少副作用的机会来更好地尊重函数式编程的范式。There is a subtle difference regarding scoping, but I would recommend understanding it well as it reveals some of important aspects of Ruby.
for
is a syntax construct, somewhat similar toif
. Whatever you define infor
block, will remain defined afterfor
as well:On the other hand,
each
is a method which receives a block. Block introduces new lexical scope, so whatever variable you introduce in it, will not be there after the method finishes:I would recommend forgetting about
for
completely, as usingeach
is idiomatic in Ruby for traversing enumerables. It also recspects the paradigm of functional programming better, by decreasing chances of side-effects.sites.each
作用域x
位于块内,而for
如果在块外部声明,则将重用x
。一般来说,最好使用each
,它可以最大限度地减少大型代码体的副作用。sites.each
scopesx
inside the block, whereasfor
will reusex
if declared outside the block. In general it's better therefore to useeach
, it minimizes side effects over large bodies of code.CBZ 答案是正确的,但不完整,因为 1.8.X 和 1.9.X 之间的行为存在差异:
1.9.2 IRB:
1.8.7 IRB:
CBZ answer is correct but incomplete since there is a difference in behavior between 1.8.X and 1.9.X:
1.9.2 IRB:
1.8.7 IRB:
CBZ的回答是正确的。为了说明这一点,请参见以下示例:
CBZ answer is correct. To illustrate this, see this example: