Ruby中的"for"是什么?

23

在Ruby中:

for i in A do
    # some code
end

与以下相同:

A.each do |i|
   # some code
end

for不是内核方法:

  • for在Ruby中具体是什么意思?
  • 是否有其他关键字可以做类似的事情?

类似于:

 total = sum i in I {x[i]}

映射到:

 total = I.sum {|i] x[i]}
3个回答

46

这几乎是一种语法糖。一个区别是,虽然for将使用其周围代码的范围,each在其块内创建一个单独的范围。比较以下内容:

for i in (1..3)
  x = i
end
p x # => 3

对比

(1..3).each do |i|
  x = i
end
p x # => undefined local variable or method `x' for main:Object

哇,如此微妙,但当我遇到这样的情况时会变得非常方便。谢谢! - sivabudh
实际上,你的第二个例子会抛出NameError: undefined local variable or method 'i' for main:Object的错误。这是因为你漏掉了一个do - Jakub Hampl

14

for 只是 each 方法的语法糖。可以通过运行以下代码来看到这一点:

for i in 1 do
end

这会导致错误:

NoMethodError: undefined method `each' for 1:Fixnum

3
-1 是因为这两者之间存在差异,并且它们并不总是等价的。 - user2398029

9

for循环只是语法糖。

来自the pickaxe:

For ... In

Earlier we said that the only built-in Ruby looping primitives were while and until. What's this ``for'' thing, then? Well, for is almost a lump of syntactic sugar. When you write

for aSong in songList
  aSong.play
end

Ruby translates it into something like:

songList.each do |aSong|
  aSong.play
end

The only difference between the for loop and the each form is the scope of local variables that are defined in the body. This is discussed on page 87.

You can use for to iterate over any object that responds to the method each, such as an Array or a Range.

for i in ['fee', 'fi', 'fo', 'fum']
  print i, " "
end
for i in 1..3
  print i, " "
end
for i in File.open("ordinal").find_all { |l| l =~ /d$/}
  print i.chomp, " "
end

produces:

fee fi fo fum 1 2 3 second third

As long as your class defines a sensible each method, you can use a for loop to traverse it.

class Periods
  def each
    yield "Classical"
    yield "Jazz"
    yield "Rock"
  end
end


periods = Periods.new
for genre in periods
  print genre, " "
end

produces:

Classical Jazz Rock
Ruby没有其他关键字用于列表推导(例如您上面制作的总和示例)。for不是一个非常流行的关键字,通常更喜欢使用方法语法(arr.each {})。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接