2016-05-14 75 views
0

当尝试一个块传递给数总和法:传递块时,没有方法误差的方法

def sum(list, &block) 
    list.find_all{yield}.reduce(0, :+) 
end 
sum([12, 14, 0, 7, 56, 0]) {|i| i % 2 == 0} 

我得到这个错误:

NoMethodError: undefined method `%' for nil:NilClass

我的方法无法识别i作为我列表中的一个元素。我不知道如何修复它。任何建议?

回答

0
list.find_all { |i| yield i }.reduce(0, :+) 

或等价

list.find_all(&block).reduce(0, :+) 

您最初写在列表中搜寻的内容,使每个元素你yield - 这将不带参数调用该块,i被分配nil,并nil % 2是坏。

+0

非常感谢。你能告诉我我在哪里可以在ruby API文档中找到该语法?我无法在ruby文档中找到它。 –

+0

如果您正在讨论我使用过的&block,[proc to block conversion](http://docs.ruby-lang.org/en/2.0.0/syntax/calling_methods_rdoc.html#label-Proc+to+块+转化率)。 'block'是'Proc'对象,由[block argument](http://docs.ruby-lang.org/en/2.0.0/syntax/methods_rdoc.html#label-Block+Argument)创建'&block '用你自己的代码。 – Amadan