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!
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) %>
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 }