Iterators: inject and reduce

There are various ways to iterate in Ruby. Presumably the most common is Enumerator#each, even though there are dedicated alternatives for certains use cases. Accumulation is such a particular iteration. An accumulation example with each looks like:

sum = 0
(1..10).each { |number| sum += number }  # => 1..10
sum # => 55

That is awkward for some reasons: 1. The result variable has to be initialized 2. Enumerator#each does express only little about what is going on in the iteration 3. The iteration return value is not the result of the iteration

Ruby provides Enumerable#inject and Enumerable#reduce for accumulations, whereas inject is the alias of reduce. Basically the alias only should be used, if it increases the readability.
The same accumulation example with reduce:

(1..10).reduce(0) { |sum, number| sum += number }  # => 55

It is not only that 3 LOC were boiled down into a single line. The real benefit is its increased readability. Just by reading the iterator, it is clear that it returns an accumulation result. In this case it is a sum.
It also could be some HTML tags, generated by a Ruby on Rails helper method:

def names names
  names.inject(''.html_safe) { |name, html| html << content_tag(:span, name) }

The whole issue can be expressed even more concise. The pure Ruby summation example once again:

(1..10).reduce(:+) # => 55