Reputation: 57
I have 8 transactions in a ruby array (@transactions) and each transaction has a number value associated with them that I need to add to get one number, the sum of each transaction's number. How can I use a code block to add the numbers together? Is a code block the best way to iterate through to get a total?
@transactions.each do | t |
# ??
end
Upvotes: 0
Views: 101
Reputation: 1104
Try below code. Although this question might have been answered long before. You should once google the question before you post it.
@transaction.inject(0){|sum,x| sum + x.number_value }
Upvotes: -1
Reputation: 118271
Do as below Using Enumerable#reduce
:
@transactions.reduce(0) { |sum,ob| sum + ob.number_val }
Upvotes: 2