Đỗ Tiến Đỗ Tiến - 1 year ago 57
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, :+)
sum([12, 14, 0, 7, 56, 0]) {|i| i % 2 == 0}

Answer Source
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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download