public
Last active

Formatting a 2D array as an HTML table

  • Download Gist
2d_table.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
def wrap(s, tag, attr={}, &b)
s = [s] unless s.is_a? Array
attr = attr.empty? ? '' : " #{attr.map{|k,v| "#{k}='#{v}'"}.join(" ")}"
out = "<#{tag}#{attr}>"
out += s.inject("") {|m,o| m+="#{block_given? ? (yield o) : o}"}
out += "</#{tag}>"
end
 
def format_table(data)
wrap(data,"table",border: 1) do |row|
wrap(row,"tr", valign: :center) do |cell|
wrap(cell,"td", align: :right)
end
end
end
 
data=[[1,2,3,4],[5,6,7,8]]
 
format_table(data)
# => <table border='1'><tr valign='center'><td align='right'>1</td><td align='right'>2</td><td align='right'>3</td><td align='right'>4</td></tr><tr valign='center'><td align='right'>5</td><td align='right'>6</td><td align='right'>7</td><td align='right'>8</td></tr></table>
out.html
HTML
1
<table border='1'><tr valign='center'><td align='right'>1</td><td align='right'>2</td><td align='right'>3</td><td align='right'>4</td></tr><tr valign='center'><td align='right'>5</td><td align='right'>6</td><td align='right'>7</td><td align='right'>8</td></tr></table>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.