How does this ruby injection magic work?

前端 未结 3 1529
余生分开走
余生分开走 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条回答
  •  猫巷女王i
    2020-12-11 07:25

    There's no magic, symbol (method) is just one of the possible parameters. This is from the docs:

      # enum.inject(initial, sym) => obj
      # enum.inject(sym)          => obj
      # enum.inject(initial) {| memo, obj | block }  => obj
      # enum.inject          {| memo, obj | block }  => obj
    

    Ours case is the second one.

    You can also rewrite it with traditional block:

    op = :+   #  parameter of inject call
    [1,2,3,4,5,6,7].inject {|sum, x| sum.send(op, x)} #  also returns 28
    

    (to answer "how does it work" part)

提交回复
热议问题