Symbol vs. Proc in `Enumerable # inject`

Given that it Enumerable#inject

can accept either a character or a block as a method to be used on iteration, as explained in the answer to this question , is there any reason to use &

in combination with Symbol#to_proc

internally Enumerable#inject

? The following pairs return the same result:

[1, 2, 3, 4, 5].inject(:+)
[1, 2, 3, 4, 5].inject(&:+)

[:a, :b, :c].inject({a: {b: {c: 1}}}, :fetch)
[:a, :b, :c].inject({a: {b: {c: 1}}}, &:fetch)

      

Is there any use case where using a symbol and using a block (created &

) have different results? Are there any cases where one can use one instead of the other?

+3


source to share


1 answer


If you need to support older versions of Ruby (1.8.6 or older), and you are using a library that defines Symbol#to_proc

for those versions (for example, active support), the using version &

will work and others will not.



Also, the only differences between the two versions are that the version using the symbol is faster and that the version using the symbol &

will be affected if you override Symbol#to_proc

- although I can't think of a case where this would be useful. So no, unless you need to support Ruby 1.8.6, there is no reason not to use the symbol form.

+4


source







All Articles