Monthly Archives: May 2015

Ruby #each .vs. #inject in the Presence of Side-Effects

Note the difference between:

numbers.inject(0) {| sum, x | sum + x }


sum = 0
numbers.each {| x | sum += x }

… the former is obviously preferred.


If the #inject result value is mutated *and* the result value is used elsewhere (or implicitly returned), use a local variable with #each, instead of #inject.

Continue reading