Rubin is trying to understand the new notation. (type (:) vs select (&: even?), why does anyone have it?)

So, I just found out that instead of writing things like:

[1,2,3,4,5].inject {|x,y| x + y} => 15 

I could write

 [1,2,3,4,5].inject(:+) => 15 

I also found out that instead of writing

 [1,2,3,4,5].select {|x| x.even?} => [2,4] 

I could write

 [1,2,3,4,5].select(&:even?) => [2,4] 

My question is why one (chooses) uses & , and the other (injection) doesn't. I am sure that : due to the fact that even? and + processed by characters, but I would like to explain why & used in one and why it is used :

In addition, I know that I could make these not only inject and select notations.

Many thanks!

+7
source share
1 answer
Operator

& in this case converts the character to proc. So, the code does this under the hood:

 [1,2,3,4,5].select {|elem| elem.send :even? } # => [2, 4] 

The inject method inject recognizes the need for this shortcut method specification and adds special processing when a character passes as a parameter. So in this case, it basically executes the & operator.

why one (chooses) uses a and the other (squirts) doesn't

Because no one implemented select this way. Ruby is open source, they can even take your patch. Go ahead and fix it :)

PS: But if it depends on me, I would instead remove the special treatment injection. It feels a little redundant and confusing in the presence of Symbol#to_proc (which uses the & operator).

+10
source

All Articles