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?