1

I am very new to ruby and still in learning phase. I recently came across statements like .inject(:+) and a.select(&:even?). I do not know what :+ or &: does exactly.

  1. Can someone please help me understand what it is?

  2. Also, are there any other similar operators present in ruby, if yes, can you please point me to a reference where I can learn more about these operators.

I have googled about these operators but I could not find a solid document or resource which talks specifically about these kind of operators and hence, I am here seeking the community's help.

=> [1,2,3,4,5].inject(:+) 
=> 15
=> [1,2,3,4,5].select(&:even?) 
=> [2,4]
Abhishek Garg
  • 105
  • 3
  • 8
  • 5
    There is a good explanation [here](https://medium.com/@sihui/proc-code-block-conversion-and-ampersand-in-ruby-35cf524eef55). Being new to Ruby I think you may have some trouble following that. I suggest that, for now, you should just think of `arr.inject(:+)` as being *shorthand* for `arr.inject { |tot,n| tot + n }` and `arr.select(&:even?)` as being *shorthand* for `arr.select { |n| n.even? }`. Incidentally, I'm sure this question has been asked many times at SO, so don't be surprised if others post links to those other answers. Not too worry if your question is closed for that reason. – Cary Swoveland Jun 19 '19 at 05:53
  • 5
    You have actually asked two questions. The first is when `inject` has an argument that is a symbol which is the name of a method. See the doc [Enumerable#inject](http://ruby-doc.org/core-2.5.1/Enumerable.html#method-i-inject) (a.k.a. `reduce`) for an explanation. The second is when `select` has an "argument" that is the name of a method (`:even?`) preceded by `&`. The `&` first invokes the method `to_proc` on `:even?` to convert the method to a *proc*, then it calls the proc. P.S. As I predicted, your question, being a *dup*, has been closed. Don't lose sleep over that. – Cary Swoveland Jun 19 '19 at 06:17
  • 1
    .select(&:even?) is the same as .select { |x| x.even? } Whenever you see (&:method) it means the same as { |x| x.method } – Mark Jun 19 '19 at 09:12
  • 1
    @Mark, yes, except for methods like `reduce`, `each_with_object` and `each_with_index`, that add an additional block variable. – Cary Swoveland Jun 19 '19 at 12:50
  • That's a good point :) – Mark Jun 19 '19 at 13:20

0 Answers0