Tom Lehman Tom Lehman - 1 year ago 81
Ruby Question

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:


Answer Source

Use the XMLBuilder for this:

data = [{"col1"=>"v1", "col2"=>"v2"}, {"col1"=>"v3", "col2"=>"v4"}]
xm = => 2)
xm.table { { data[0].keys.each { |key|}}
  data.each { |row| { row.values.each { |value|}}}
puts "#{xm}"


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download