How does “(1..4).inject(&:+)” work in Ruby

From Ruby documentation:

If you specify a symbol instead, then each element in the collection will be passed to the named method of memo

So, specifying a symbol is equivalent to passing the following block:
{|memo, a| memo.send(sym, a)}

If you do not explicitly specify an initial value for memo, then uses the first element of collection is used as the initial value of memo.

So, there is no magic, Ruby simply takes the first element as the initial value and starts injecting from the second element. You can check it by writing [].inject(:+): it returns nil as opposed to [].inject(0, :+) which returns 0.

Edit: I didn’t notice the ampersand. You don’t need it, inject will work with a symbol. But if you do write it, the symbol is converted to block, it can be useful with other methods

Leave a Comment