I’m new to Ruby, and I’m having a strange problem with the inject method.
When I do:
(1..10).inject(0) {|count,x| count + 1}
the result is 10, as expected. But when I do
(1..10).inject(0) {|count,x| count + 1 if (x%2 == 0)}
I get an error:
NoMethodError: undefined method `+' for nil:NilClass
from (irb):43
from (irb):43:in `inject'
from (irb):43:in `each'
from (irb):43:in `inject'
from (irb):43
I don’t really understand why (presumably) count is nil in the second example, but not the first. In any case, how would I count evens from 1 to 10 using inject?
The expression
count + 1 if (x%2 == 0)returnsnilwhen the condition isn’t true, whichcountgets set to because that’s the nature of the inject method.You could fix it by returning
count + 1when it’s an even number and justcountwhen it’s not:A completely different solution is to use
selectto select the even numbers and use theArray#lengthmethod to count them.