简体   繁体   中英

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!

您可以使用inject来累加count并获得所有书籍的总数:

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

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) %>
@book.collect(&:count).sum

试试看@books.sum(:count)这将返回您的总和

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM