test
test

Reputation: 2466

Ruby Rails total value of loop each

I have a loop like this listing all count numbers like 2,44,11 etc., how do I calculate total number?

<% @book.each do |book| %>
<div><%= book.count %></div>
<% end %>

Thanks!

Upvotes: 0

Views: 1690

Answers (4)

user229044
user229044

Reputation: 239312

You can use @books.sum, and pass it a proc which is invoked for each record, returning the number you want to add to the sum. Using Proc#to_sym gives you a very succinct syntax:

@books.sum(&:count)

<% @book.each do |book| %>
<div><%= book.count %></div>
<% end %>

Total books: <%= @books.sum(&:count) %>

Upvotes: 3

Nitin Jain
Nitin Jain

Reputation: 3083

try it out @books.sum(:count) this will return you sum

Upvotes: 1

arun15thmay
arun15thmay

Reputation: 1062

@book.collect(&:count).sum

Upvotes: 2

vee
vee

Reputation: 38645

You can use inject to add up the counts and get the total count of all the books:

@book.inject(0) { |total, book| total + book.count }

Upvotes: 3

Related Questions