Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate an HTML table from an array of hashes in Ruby

What's the best way (ideally a gem, but a code snippet if necessary) to generate an HTML table from an array of hashes?

For example, this array of hashes:

[{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]

Should produce this table:

<table>
  <tr><th>col1</th><th>col2</th></tr>
  <tr><td>v1</td><td>v2</td></tr>
  <tr><td>v3</td><td>v4</td></tr>
</table>
like image 415
Tom Lehman Avatar asked Apr 13 '10 23:04

Tom Lehman


1 Answers

# modified from Harish's answer, to take care of sparse hashes:

require 'builder'

def hasharray_to_html( hashArray )
  # collect all hash keys, even if they don't appear in each hash:
  headers = hashArray.inject([]){|a,x| a |= x.keys ; a}  # use array union to find all unique headers/keys                              

  html = Builder::XmlMarkup.new(:indent => 2)
  html.table {
    html.tr { headers.each{|h| html.th(h)} }
    hashArray.each do |row|
      html.tr { row.values.each { |value| html.td(value) }}
    end
  }
  return html
end
like image 105
Tilo Avatar answered Oct 07 '22 18:10

Tilo