Đỗ Tiến Đỗ Tiến - 6 months ago 9
Ruby Question

No method error when passing a block to a method

I am learning Ruby, I get this error when trying to pass a block to the sum method. I've been searching for the solution for a while, but couldn't find any. I know that somehow my method couldn't understand the i as an element in my list, but I don't know how fix it. Any suggestion?


NoMethodError: undefined method `%' for nil:NilClass


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

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

or equivalently

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

What you originally wrote searched through the list so that for each element you yield - this would invoke the block with no parameters, i gets assigned nil, and nil % 2 is bad.