【问题标题】:What is "for" in RubyRuby 中的“为”是什么
【发布时间】:2010-09-14 09:41:04
【问题描述】:

在 Ruby 中:

for i in A do
    # some code
end

等同于:

A.each do |i|
   # some code
end

for 不是内核方法:

  • ruby 中的“for”到底是什么
  • 有没有办法使用其他关键字来做类似的事情?

类似:

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

映射到:

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

【问题讨论】:

    标签: ruby metaprogramming


    【解决方案1】:

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

    【讨论】:

    • 哇,如此微妙,但当我遇到这样的事情时会变得很方便。谢谢!
    • 实际上你的第二个例子抛出了NameError: undefined local variable or method 'i' for main:Object。这是因为您缺少do
    • @JakubHampl 我修好了。谢谢!
    【解决方案2】:

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

    for i in 1 do
    end
    

    这会导致错误:

    NoMethodError: undefined method `each' for 1:Fixnum
    

    【讨论】:

    • -1 因为两者是有区别的,而且它们并不总是等价的。
    【解决方案3】:

    For 只是语法糖。

    来自the pickaxe

    为了……在

    之前我们说过,唯一内置的 Ruby 循环原语是 while 和 until。那么,这个“为”的东西是什么?好吧, for 几乎是一大堆语法糖。当你写

    for aSong in songList
      aSong.play
    end
    

    Ruby 将其翻译成如下内容:

    songList.each do |aSong|
      aSong.play
    end
    

    for 循环和 each 形式之间的唯一区别是在主体中定义的局部变量的范围。这在第 87 页进行了讨论。

    您可以使用 for 迭代任何响应每个方法的对象,例如数组或范围。

    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
    

    产生:

    fee fi fo fum 1 2 3 second third
    

    只要你的类定义了一个明智的 each 方法,你就可以使用 for 循环来遍历它。

    class Periods
      def each
        yield "Classical"
        yield "Jazz"
        yield "Rock"
      end
    end
    
    
    periods = Periods.new
    for genre in periods
      print genre, " "
    end
    

    产生:

    Classical Jazz Rock
    

    Ruby 没有用于列表推导的其他关键字(如您在上面所做的 sum 示例)。 for 不是一个非常流行的关键字,通常首选方法语法(arr.each {})。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-08
      • 2011-09-10
      • 1970-01-01
      • 2016-09-17
      • 2013-01-31
      • 2010-10-29
      相关资源
      最近更新 更多