7

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>
the Tin Man
  • 158,662
  • 42
  • 215
  • 303
sybind
  • 3,418
  • 5
  • 25
  • 25

2 Answers2

4

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
mu is too short
  • 426,620
  • 70
  • 833
  • 800
2

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>
JasonMArcher
  • 14,195
  • 22
  • 56
  • 52
sosborn
  • 14,676
  • 2
  • 42
  • 46