user3245766
user3245766

Reputation: 57

How to add within a .each code block

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

Answers (3)

Saurabh
Saurabh

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

Arup Rakshit
Arup Rakshit

Reputation: 118271

Do as below Using Enumerable#reduce:

@transactions.reduce(0) { |sum,ob| sum + ob.number_val }

Upvotes: 2

Matt
Matt

Reputation: 20786

Ruby on rails has a sum function:

@transactions.sum { |t| t.number_value }

or if you want additional brevity

@transactions.sum(:number_value)

Upvotes: 4

Related Questions