【发布时间】: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?
【问题讨论】:
有一个非常简单的问题,为什么当我这样定义一个块时:
def test
yield
end
a=test{7} => a=7
当我定义这样的块时
def test(n)
n.times{ yield }
end
a=test(4){7} => 4
为什么返回值变成n not yield?
【问题讨论】:
如果您查看源代码,times 方法将返回它运行的次数,而不是它运行的块的结果。
【讨论】:
Self 是源代码中的num。如果你使用 -15 它会返回它,但它不是它运行的次数。不过,您的所有其他答案都会获得 +1!
它返回来自Integer#times 的值(恰好与您调用该方法的编号相同 - 可以在the Rubinius source 或RubySpec 上看到)而不是块返回值。
由于Integer#times 多次调用该块,您基本上有两种选择:
将所有调用的结果组合在一个数组上并返回。
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]
将从块返回的最后一个值存储在一个变量中,并返回它:
def test(n)
result = nil
n.times { |current| result = yield(current) }
result
end
test(4) { |n| n * 2 } # => 6
【讨论】:
self,这是调用times的整数。