Reputation: 2466
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
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