How does this ruby injection magic work?

前端 未结 3 1524
余生分开走
余生分开走 2020-12-11 06:49

I saw a ruby code snippet today.

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

=> 28

[1,2,3,4,5,6,7].inject(:*)  

3条回答
  •  北海茫月
    2020-12-11 07:32

    The :+ is a symbol representing the addition message. Remember that Ruby has a Smalltalk style where just about every operation is performed by sending a message to an object.

    As discussed in great detail here, (1..100).inject(&:+) is valid syntax in earlier versions where Rails has added the to_proc extension to Symbol.

    The ability to pass just a symbol into inject was new in 1.9 and backported into 1.8.7.

提交回复
热议问题