Reputation: 3588
I have three arrays I'd like to arrange vertically in an HTML table. Each array will have its data populated in a column from top to bottom.
For example, I have three arrays:
fruit = ['pear', 'apple', 'orange']
veges = ['corn', 'radish', 'lettuce']
meat = ['beef', 'chicken', 'pork']
I want the table to look like this:
<table>
<tr>
<td>
pear
</td>
</tr>
<tr>
<td>
corn
</td>
</tr>
<tr>
<td>
beef
</td>
</tr>
<tr>
<td>
apple
</td>
</tr>
<tr>
<td>
radish
</td>
</tr>
<tr>
<td>
chicken
</td>
</tr>
<tr>
<td>
orange
</td>
</tr>
<tr>
<td>
lettuce
</td>
</tr>
<tr>
<td>
pork
</td>
</tr>
</table>
Upvotes: 7
Views: 3729
Reputation: 434685
I'd probably use Array#transpose
to rearrange things to match what your <table>
should look like:
rows = [ fruit, veges, meat ].transpose
Now rows
will look like:
[
["pear", "corn", "beef"],
["apple", "radish", "chicken"],
["orange", "lettuce", "pork"]
]
and generating your table is a simple matter of iterating over rows
:
%table
- rows.each do |row|
%tr
- row.each do |food|
%td= food
Upvotes: 4
Reputation: 14694
Take a look at this website: Generate vertically-ordered HTML table in Ruby
Here is the relevant code (the instance variables in this example are used simply for clarity in identifying what controls the number of columns and rows):
<table>
<tbody>
<% 0.upto(@rows_per_column-1).each do |row| %>
<tr>
<% 0.upto(@columns-1).each do |column| %>
<% index = row + (column * @rows_per_column) %>
<td><%= index %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
Upvotes: 2