Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Building a table in erb by iterating through 3 different arrays

I have the following arrays in my controller (they each have the same number of elements)

@account_names => => ["Cleveland", "Denver", "Houston", "LA", "Louisville", "Minneapolis", "Nashville", "Phoenix", "Reno", "San Diego", "San Francisco", "Seattle", "South Florida", "Utah", "Vancouver", "DC"]
@combined_conversions => [0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 0, 6, 0, 0, 0, 0]
@combined_spend => [103.65, 86.88, 142.17, 324.4, 86.84, 135.45, 48.11, 149.42, 44.46, 94.36, 285.15, 211.98, 224.61, 77.11, 23.39, 29.82]

I'm trying to create a table in my view like so

<table class="table table-hover">
<tr>
  <th>Name</th>
  <th>Conversions</th>
  <th>Spend</th>
</tr>

<tr>
<% @account_names.each do |name| %>                    
  <td><%= name %><td>
<% end %>

<% @combined_conversions.each do |conversion| %>
  <td><%= conversion %></td>
<% end %>

<% @combined_spend.each do |spend| %>
  <td><%= spend %></td>
<% end %>                    
</tr>
</table>

But the HTML output that I get is one big row

<tr>
  <td>Cleveland<td>
  <td>Denver<td>
  <td>Houston<td>
  <td>LA<td>
  <td>Louisville<td>
  <td>Minneapolis<td>
  <td>Nashville<td>
  <td>Phoenix<td>
  <td>Reno<td>
  <td>San Diego<td>
  <td>San Francisco<td>
  <td>Seattle<td>
  <td>South Florida<td>
  <td>Utah<td>
  <td>Vancouver<td>
  <td>DC<td>
  <td>0</td>
  <td>0</td>
  <td>2</td>
  <td>0</td>
  <td>0</td>
  <td>0</td>
  etc.

When really I'd like it to look like

<tr>
  <td>Cleveland<td>
  <td>0<td>
  <td>103.65<td>
</tr>
<tr>
  <td>Denver<td>
  <td>0<td>
  <td>86.88<td>
</tr>

If I try it with just one array it works properly placing one element to each row

<tr>
<% @account_names.each do |name| %>                    
  <td><%= name %><td>
</tr>
<% end %>
like image 741
macoughl Avatar asked Mar 07 '14 22:03

macoughl


1 Answers

You would probably write it like this:

  <% @account_names.each_with_index do |name, index| %>                    
    <tr>
      <td><%= name %><td>
      <td><%= @combined_conversions[index] %></td>
      <td><%= @combined_spend[index] %></td>
    </tr>
  <% end %>

Since each key in each array maps 1-to-1 with its values in the corresponding arrays, you can just reference the other arrays and find the same index there. "Cleveland" will show 0 in the second column and "103.65" in the third.

like image 199
Ryan Bigg Avatar answered Sep 19 '22 00:09

Ryan Bigg