Slowboy
Slowboy

Reputation: 601

Adding values together from loop

I have this each loop:

<% User.group(:team).count.each do |team, count| %>
  <%= "The '#{team}' has '#{count} User'" %>
<% end %>

The output is like this:

The 'Vikings' has '1 User' The  
'Redsocks' has '3 User' The 'Giants' has '1 User' The 
'Milan' has '2 User' The 'IKS' has '1 User' The 'Clampers' has '1 User'

I want count to be added together, and team to be added together. I want the output be something like:

the app has " 9 " users supporting "6 " different teams

Can someone advise me on how to do that?

Upvotes: 0

Views: 60

Answers (1)

MrYoshiji
MrYoshiji

Reputation: 54882

This is a way to do it, but I strongly recommend you to move this count logic somewhere else than your view(s)

<% teams_count = 0 %>
<% users_count = 0 %>
<% team_users_details = [] %>
<% User.group(:team).count.each do |team, count| %>
  <% team_users_details << "The '#{team}' has '#{count} User'" %>
  <% teams_count += 1 %>
  <% users_count += count %>
<% end %>

<%= "The app has '#{users_count}' users supporting '#{teams_count}' different teams" %>
<%= team_users_details.join(' ') %>

Upvotes: 2

Related Questions