Taylor Tompkins
Taylor Tompkins

Reputation: 71

What is (:+) called and what is it's function in this line of code?

totals = party.transpose.map { |r| r.reduce(:+) }

Here I am reducing a 2D array into a 1D array, and I'd just like to know more about (:+). I used it a few times in my code but I don't fully understand it, i.e. what it's called, when and why it's used

Upvotes: 1

Views: 55

Answers (1)

max
max

Reputation: 102423

irb(main):001:0> :+.class
=> Symbol

Its just a symbol containing the name of a method.

irb(main):004:0> 1.method(:+)
=> #<Method: Integer#+(_)>
irb(main):005:0> 1.method(:+).call(1)
=> 2

Enumerable#reduce and Enumerable#inject take a symbol, string or a proc and will call that method for each iteration of the loop.

[1,2,3].reduce(:+)
[1,2,3].reduce('+')
[1,2,3].reduce(&:+)

All three of these return 6. And they are short for:

[1,2,3].reduce { |sum, n| sum + n }

The reason symbols are most commonly used is that they are interned and thus use less memory then a non-frozen string attribute and they are also easier to type.

And finally with Ruby 2.4 you can just use Enumerable#sum instead:

[1,2,3].sum

Upvotes: 3

Related Questions