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!
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.
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 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.
The sum of two numbers is the answer you get when you add them both together.
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)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With