Ruby中的" for"是什么

时间:2020-03-06 14:57:11  来源:igfitidea点击:

在Ruby中:

for i in A do
    # some code
end

是相同的:

A.each do |i|
   # some code
end

" for"不是内核方法:

  • 红宝石中的" for"到底是什么
  • 有没有办法使用其他关键字来做类似的事情?

就像是:

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

映射到:

total = I.sum {|i] x[i]}

解决方案

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

for i in 1 do
end

这导致错误:

NoMethodError: undefined method `each' for 1:Fixnum

对于只是语法糖。

从镐:

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 {}")。

这几乎是语法糖。一个区别是,尽管" 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