How to fill a table with vertical data?

I have three arrays that I would like to arrange vertically in an HTML table. Each array will have its own data, filled 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>
+5
source share
2 answers

I would probably use Array#transposeto reorder things according to yours <table>:

rows = [ fruit, veges, meat ].transpose

Now it rowswill look like this:

[
  ["pear", "corn", "beef"],
  ["apple", "radish", "chicken"],
  ["orange", "lettuce", "pork"]
]

and generating your table is a simple question iterating over rows:

%table
  - rows.each do |row|
    %tr
      - row.each do |food|
        %td= food
+4
source

Take a look at this site: Create a vertically ordered HTML table in Ruby

( , ):

<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>
+1

All Articles