【问题标题】:Ruby yield called from within Integer#times not returning the evaluated block从 Integer#times 中调用的 Ruby yield 不返回评估的块
【发布时间】:2013-12-09 13:31:42
【问题描述】:

有一个非常简单的问题,为什么当我这样定义一个块时:

def test
yield
end

a=test{7} => a=7

当我定义这样的块时

def test(n)

n.times{ yield }
end
a=test(4){7} => 4

为什么返回值变成n not yield?

【问题讨论】:

    标签: ruby yield implicit


    【解决方案1】:

    如果您查看源代码,times 方法将返回它运行的次数,而不是它运行的块的结果。

    【讨论】:

    • 如果您查看文档,它会声明“times {|i| block } → self”(如果给定一个块),因此它会返回 self。 Self 是源代码中的num。如果你使用 -15 它会返回它,但它不是它运行的次数。不过,您的所有其他答案都会获得 +1!
    【解决方案2】:

    它返回来自Integer#times 的值(恰好与您调用该方法的编号相同 - 可以在the Rubinius source 或RubySpec 上看到)而不是块返回值。

    由于Integer#times 多次调用该块,您基本上有两种选择:

    1. 将所有调用的结果组合在一个数组上并返回。

      def test(n)
        result = []
        n.times { |current| result << yield(current) }
        result
      end
      
      # Or, leveranging Enumerator#map:
      
      def test(n)
        n.times.map { |current| yield(current) }
      end
      
      # Or, still shorter, by forwarding the block:
      
      def test(n, &block)
        n.times.map(&block)
      end
      
      test(4) { |n| n * 2 } # => [0, 2, 4, 6]
      
    2. 将从块返回的最后一个值存储在一个变量中,并返回它:

      def test(n)
        result = nil
        n.times { |current| result = yield(current) }
        result
      end
      
      test(4) { |n| n * 2 } # => 6
      

    【讨论】:

    • Times 不返回迭代次数。例如,您可以给它一个 -15,它会返回 -15,这恰好不是迭代次数。不,它实际上返回self,这是调用times的整数。
    • @vgoff true,感谢您的更正。您介意编辑答案吗?
    • 是的,实际上。否则我只会这样做。在更新答案时,您可能还想在答案中表达其他内容。我不知道。比如你的第二点可能表达的不是很清楚,你刚才说返回不是从块中返回的,而你又声明可以返回最后一个块返回的值。
    • @vgoff 谢谢,感谢您的 cmets,我能够改进它。还有什么要补充的吗?
    • 其他细微差别,当然,但我觉得这涵盖了问题。
    猜你喜欢
    • 2018-01-10
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 2018-03-15
    相关资源
    最近更新 更多