I've seen these several times but I can't figure out how to use them. The pickaxe says that these are special shortcuts but I wasn't able to find the syntactical description.
I've seen them in such contexts:
[1,2,3].inject(:+)
to calculate sum for example.
Let's start with an easier example. Say we have an array of strings we want to have in caps:
Also, you can create so called Proc objects (closures):
You can pass such a proc to a method with the & syntax:
What this does, is call to_proc on block and then calls that for every block:
Now, Rails first added the to_proc method to Symbol, which later has been added to the ruby core library:
Therefore you can do this:
Also, Symbol#to_proc is even smarter, as it actually does the following:
This means that
equals
inject accepts a symbol as a parameter, this symbol must be the name of a method or operator, which is this case is
:+
so
[1,2,3].inject(:+)
is passing each value to the method specified by the symbol, hence summing all elements in the array.source: https://ruby-doc.org/core-2.5.1/Enumerable.html