Ruby:for循环和每个循环之间有什么区别?

eck*_*kza 5 ruby syntax foreach loops flow-control

可能重复:
对于Ruby中的每个

假设我们有一个数组,就像

sites = %w[stackoverflow stackexchange serverfault]

有什么区别

for x in sites do
  puts x
end
Run Code Online (Sandbox Code Playgroud)

sites.each do |x|
  puts x
end
Run Code Online (Sandbox Code Playgroud)

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

Mla*_*vić 26

关于范围界定存在细微差别,但我建议理解它,因为它揭示了Ruby的一些重要方面.

for是一种语法结构,有点类似于if.无论你在for块中定义什么,都将在以后保持定义for:

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

for x in sites do
  puts x
end
stackoverflow
stackexchange
serverfault
#=> ["stackoverflow", "stackexchange", "serverfault"]
x
#=> "serverfault"
Run Code Online (Sandbox Code Playgroud)

另一方面,each是接收块的方法.Block引入了新的词法范围,因此无论你在其中引入什么变量,在方法完成后都不会出现:

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>'
Run Code Online (Sandbox Code Playgroud)

我建议for完全忘记,因为each在Ruby中使用是惯用的遍历可枚举的.它还通过降低副作用的可能性,更好地重新考虑了函数式编程的范例.


cbz*_*cbz 8

sites.eachx块内的范围,而如果在块外声明for则将重用x.一般来说,最好使用each它,它可以最大限度地减少大量代码的副作用.