How does this ruby ​​injection magic work?

Today I saw a ruby ​​code snippet.

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

=> 28

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

=> 5040

The attachment here is very different from what I saw before, for example

[1,2,3,4,5,6,7].inject {|sum, x| sum + x}

Please explain how it works?

+5
source share
3 answers

There is no magic, a 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

Our case is the second.

You can also rewrite it using a 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")

+6
source

: + - symbol representing the add message. Remember that Ruby has a Smalltalk style, where almost every operation is done by sending a message to the object.

, (1..100).inject(&:+) , Rails to_proc Symbol.

1.9 backported 1.8.7.

+3

As you can see in the documents , it injectcan take a block (for example, you are familiar) or a character that represents the name of a binary operator. This is a useful transcript for already defined operations.

+1
source

All Articles