Matchu's answer inspired me a lot and I modified it to self-defined methods instead of changing the built-in class (don't do this unless you have a really good reason).
In addition in generating a table, Array's structure maybe much more convenient and intuitive to access elements.
Let the whole table stored in a 2-D array, say
@table_array = [
["Name","Gender","Age"],
["Andy","M","20"],
["Mary","F","19"],
["Tony","M","18"]
]
in which each the first element serves as the table header and the rest is table content. Now we can use the well-formatted table_array and a table class attribute to generate a table html code:
def ToCell (tag,value)
value.map{ |c| "<#{tag}>#{c}</#{tag}>" }.join
end
def ToTable (table_array, table_class)
headers = "<tr>" + ToCell('th',table_array[0]) + "</tr>"
cells = table_array[1..table_array.count].map{ |each_row|
"<tr>#{ToCell('td',each_row)}</tr>"
}.join
table = "<table class=\"#{table_class}\"><thead>#{headers}</thead><tbody>#{cells}</tbody></table>"
end
and embed it in .erb file
<%= ToTable(@table_array,"table").html_safe %>
the output would be something like this if u see from the browser
<table class="table">
<thead>
<tr><th>Name</th><th>Gender</th><th>Age</th></tr>
</thead>
<tbody>
<tr><td>Andy</td><td>M</td><td>20</td></tr>
<tr><td>Mary</td><td>F</td><td>19</td></tr>
<tr><td>Tony</td><td>M</td><td>18</td></tr>
</tbody>
</table>