2008-09-30 121 views
23

在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]} 

回答

45

这几乎是语法糖。一个区别是,虽然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 
+0

哇,这么微妙,但当我遇到这样的事情时会变得方便。谢谢! – sivabudh 2011-10-08 02:20:50

14

for是用于each方法只是语法糖。这可以通过运行该代码可以看出:

for i in 1 do 
end 

这将导致错误:

NoMethodError: undefined method `each' for 1:Fixnum 
+3

-1因为两者之间的区别,他们并不总是等同。 – user2398029 2012-12-10 00:29:12

9

对于只是语法糖。

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 {})通常是首选。