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 }

.vs.

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

… the former is obviously preferred.

However:

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