在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]}
在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]}
这几乎是一种语法糖。一个区别是,虽然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
for
只是 each
方法的语法糖。可以通过运行以下代码来看到这一点:
for i in 1 do
end
这会导致错误:
NoMethodError: undefined method `each' for 1:Fixnum
for循环只是语法糖。
来自the pickaxe:
Ruby没有其他关键字用于列表推导(例如您上面制作的总和示例)。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
for
不是一个非常流行的关键字,通常更喜欢使用方法语法(arr.each {}
)。
NameError: undefined local variable or method 'i' for main:Object
的错误。这是因为你漏掉了一个do
。 - Jakub Hampl