Ruby:for循环和每个循环之间有什么区别? [英] Ruby: What is the difference between a for loop and an each loop?

查看:188
本文介绍了Ruby:for循环和每个循环之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

for Ruby in Ruby


假设我们有一个数组,像

sites =%w [stackoverflow stackexchange serverfault]





 对于网站中的x有什么区别do 
puts x
end

  sites.each do | x | 
puts x
end



对我来说,他们似乎做同样的事情,循环的的语法对我来说更清楚。有区别吗?在什么情况下这将是一个大问题?

解决方案

关于作用域有一个细微的差别,但我会建议理解它因为它揭示了Ruby的一些重要方面。


$ b
是一个语法结构,有点类似于如果。无论你在中为块定义什么,在之后仍然会定义:

  sites =%w [stackoverflow stackexchange serverfault] 
#=> [stackoverflow,stackexchange,serverfault]

在网站中做
放置x
结束
stackoverflow
stackexchange
serverfault
#=> [stackoverflow,stackexchange,serverfault]
x
#=> serverfault

另一方面,每个是接收块的方法。 Block引入了新的词法作用域,所以无论你在其中引入什么变量,在方法结束后都不会出现在这里:

  sites.each do | y | 
puts y
end
stackoverflow
stackexchange
serverfault
#=> [stackoverflow,stackexchange,serverfault]

NameError:未定义局部变量或方法`y'for#< Object:0x855f28 @ hhh =hello> (irb)
:/ usr / bin / irb:12:在< main> b
$ b

我会建议完全忘记,因为使用每个都是惯用的用于遍历枚举的Ruby。它还通过减少副作用的机会来更好地回顾功能性程序设计的范例。

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?

解决方案

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 to if. Whatever you define in for block, will remain defined after for as well:

sites = %w[stackoverflow stackexchange serverfault]
#=> ["stackoverflow", "stackexchange", "serverfault"]

for x in sites do
  puts x
end
stackoverflow
stackexchange
serverfault
#=> ["stackoverflow", "stackexchange", "serverfault"]
x
#=> "serverfault"

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:

sites.each do |y|
  puts y
end
stackoverflow
stackexchange
serverfault
#=> ["stackoverflow", "stackexchange", "serverfault"]
y
NameError: undefined local variable or method `y' for #<Object:0x855f28 @hhh="hello">
    from (irb):9
    from /usr/bin/irb:12:in `<main>'

I would recommend forgetting about for completely, as using each is idiomatic in Ruby for traversing enumerables. It also recspects the paradigm of functional programming better, by decreasing chances of side-effects.

这篇关于Ruby:for循环和每个循环之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆