3

Given that Enumerable#inject can take either a symbol or a block as the method to be used in the iteration, as explained in an answer to this question, is there any reason to use the & in conjunction with Symbol#to_proc within 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 by &) have different results? Are there any cases where one can be used and not the other?

Community
  • 1
  • 1
sawa
  • 165,429
  • 45
  • 277
  • 381

1 Answers1

4

If you have to support old versions of Ruby (1.8.6 or older) and you're using a library that defines Symbol#to_proc for those versions (like active support), the version using & will work and the other will not.

Other than that the only differences between the two versions are that the version using a symbol is faster and that the version using & will be affected if you redefine Symbol#to_proc - though I can't think of a case where that'd be useful. So no, if you don't need to support Ruby 1.8.6, there's no reason to not use the symbol form.

sepp2k
  • 363,768
  • 54
  • 674
  • 675