I was expecting Enumerable#inject
would be returning an enumerator like other methods and was passing it a block; but it was throwing error. Tried the following in pry
:
>> numbers = (1..12)
=> 1..12
>> numbers.each_with_index
=> #<Enumerator: ...>
>> numbers.each_with_index.map
=> #<Enumerator: ...>
>> numbers.inject(0)
TypeError: 0 is not a symbol
from (pry):18:in `inject'
I was expecting to use it as follows:
numbers = (1..12)
block = lambda { |sum, digit| sum + digit }
numbers.inject(0) { |sum, digit| sum + digit } # => 78
numbers.each_with_index.map &block # => [1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23]
numbers.inject(0) &block # => 0 is not a symbol (TypeError)
Is there some reason for such an implementation?
Conceptually, Enumerator
is a type of collection. Enumerable#inject
accumulates a value across the members of a collection, it makes little sense for it to return a Enumerator
.
You can get the job done by changing numbers.inject(0) &block
to:
numbers.inject(0, &block)