I am new to Ruby and am having a weird issue with the injection method.
When I do this:
(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 message:
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 really don't understand why the (apparently) count in the second example is zero, but not the first. Anyway, how would I count evens from 1 to 10 with an injection?
ruby
Greg Charles
source share