Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sum(&:x) not working any more

I use payments.sum(&:price) in my Rails app (4.1.2). Since I updated from Ruby 1.9.3 to 2.1.2, I get these errors:

wrong number of arguments (1 for 2..3)

These variants work:

payments.map(&:price).sum
payments.to_a.sum(&:price)

Do I have to rewrite my code or do I miss something? Thank you!

like image 792
Railsana Avatar asked Jun 30 '14 19:06

Railsana


People also ask

Whats does the sum mean?

1 : the result obtained by adding numbers The sum of 4 and 5 is 9. 2 : a problem in arithmetic. 3 : a quantity of money We donated a small sum. 4 : the whole amount Two trips is the sum of my travel experience.

What is the sum in math?

A summation, also called a sum, is the result of arithmetically adding numbers or quantities. A summation always contains a whole number of terms. There can be as few as two terms, or as many as a hundred, a thousand, or a million. Some summations contain infinitely many terms.

What is an example of a sum?

What is a sum? A mathematical sum or maths sum is the result of adding two or more numbers together. It is the total of the numbers added together. For example, the sum of 3 and 7 is 10.

Does sum mean add or subtract?

The sum of two numbers is the answer you get when you add them both together.


2 Answers

From the documentation:

sum(*args)

Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there's no row. See calculate for examples with options.

Person.sum(:age) # => 4562

it seems that your code should be without the &:

payments.sum(:price)
like image 94
Uri Agassi Avatar answered Oct 15 '22 05:10

Uri Agassi


If you had run this in Rails 4.0, you would receive the following deprecation warning:

DEPRECATION WARNING: Calling #sum with a block is deprecated and will be removed in Rails 4.1. If you want to perform sum calculation over the array of elements, use ‘to_a.sum(&block)’.

This is referring to the method Relation#sum which previously worked in Rails 3.2 when given a block.

As others have answered, you either need to use payments.sum(:price) if price is a database column, or use payments.to_a.sum(&:price) if price is an instance method.

like image 33
Brian Nguyen Avatar answered Oct 15 '22 05:10

Brian Nguyen