0

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!

4 Answers 4

3

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) %>
Sign up to request clarification or add additional context in comments.

2 Comments

sorry im newb where should i put this ? inside of the loop ?
No, just wherever you want to get the sum of counts. See update.
3

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 }

Comments

2
@book.collect(&:count).sum

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.