2

I'm trying to present a ruby Array of arrays, which I've parsed from a CSV text input, as a HTML table.

The parsing has separated out the input into arrays of rows with equal columns, from which it's created an array of row arrays.

Presentation needs to accommodate any combination of rows or columns and treat the first array (index = 0) as the table header.

This is in my model:

class Size < ActiveRecord::Base

attr_accessor :chart_options, :test
attr_accessible :account_id, :chart, :name

belongs_to :account

def test
'<it>hello</it>'
end


def chart_options

require 'csv'   

@chart_options = CSV.parse(chart , {:headers => true, :col_sep => "|", :row_sep     => :auto, :skip_blanks => true})

@table = CSV.parse(chart, {:headers => true, :col_sep => "|", :row_sep => :auto, :skip_blanks => true}).to_a

@chart_options
@table

end

end

And this is the output:

["UK ", " USA ", " Euro "]
["Small UK ", " Small US ", " Small Euro "]
["Med UK ", " Med US ", " Med Euro "]
["Large UK ", " Large US ", " Large Euro"]

UPDATED SOLUTION:

<table class="size_chart table table-striped">
    <thead>
        <tr>
          <% @headers.each do |header| %>
            <th><%= header %></th>
          <% end %>
        </tr>
    <thead>
    <tbody>
        <% @rows.each do |row| %>
          <tr>
            <% row.each do |column| %>
              <td><%= column %></td>
            <% end %>
            </tr>
          <% end %>
    </tbody>
</table>
1
  • What are you asking for? Commented Apr 25, 2013 at 21:27

1 Answer 1

1
<table>
<tr>
  <% @table.delete_at(0).each do |header| %>
    <th><%= header %></th>
  <% end %>
</tr>
<% @table.each do |row| %>
  <tr>
    <% row.each do |column| %>
      <td><%= column %></td>
    <% end %>
  <% end %>
</table>

Warning: I have not tested this code, so there may be a typo, but this is the general idea, a loop in a loop.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the quick answer. Iterating over 2 arrays worked. I've included the snippet from my final code above.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.