1

I have code like this

 list << num if num.to_s.split("").map(&:to_i).map(&:factorial).inject(:+) == num

It works, and I was wondering how inject works without the & (ampersand) in front of the :+. I am asking for someone to explain what the differences are between :+ and &:+.

sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

6

&:+ is translated to a proc, while :+ is a Symbol. inject supports receiving symbols, which is translated internally to a proc:

If you specify a block, then for each element in enum the block is passed an accumulator value (memo) and the element. If you specify a symbol instead, then each element in the collection will be passed to the named method of memo. In either case, the result becomes the new value for memo. At the end of the iteration, the final value of memo is the return value for the method.

Uri Agassi
  • 36,848
  • 14
  • 76
  • 93