JoMojo
JoMojo

Reputation: 404

Ruby array to HTML table

I'm trying to figure out a way to take a Ruby array and create an HTML table. The array is dynamic, its contents change depending on user options and inputs so the HTML tables also need to be dynamic.

The array look something like this:

array = [[a, 1, 2 ,3], [a, 1, 2 ,3], [a, 1, 2 ,3], [b, 1, 2 ,3], [b, 1, 2 ,3], [b, 1, 2 ,3], [c, 1, 2 ,3]]

What I would like to do is first group or split the array in the following way (though this might not be necessary, I don't know).

array1 = [[a, 1, 2 ,3], [a, 1, 2 ,3], [a, 1, 2 ,3]]
array2 = [[b, 1, 2 ,3], [b, 1, 2 ,3], [b, 1, 2 ,3]]
array3 = [[c, 1, 2 ,3]] 

Then outputting each of the new arrays in a separate HTML tables, where a, b, c could be like a header/title and then sub element would be a new row to the that table. In short I'd like to be able to control where each element is placed in the table.

I know my description probably isn't too clear but this is way beyond my very limited skill set and even difficult to explain what I want to achieve. :)

edit: here's my attemp at visualizing what I'm trying to accomplish... html output result

Upvotes: 1

Views: 5009

Answers (2)

Reactormonk
Reactormonk

Reputation: 21740

more or less stateless :-)

a = [["a", 1, 2 ,3], ["a", 1, 2 ,3], ["a", 1, 2 ,3],
     ["b", 1, 2 ,3], ["b", 1, 2 ,3], ["b", 1, 2 ,3], ["c", 1, 2 ,3]]

grouped = a.group_by{|t| t[0]}.values
header = "<tr><td>Name</td> <td>Length</td> <td>Width</td> <td>Depth</td> </tr>"
table = grouped.map do |portion|
  "<table>\n" << header << "\n<tr>" << portion.map do |column|
    "<td>" << column.map do |element|
      element.to_s
    end.join("</td><td>") << "</td>"
  end.join("</tr>\n<tr>") << "</tr>\n</table>\n"
end.join("\n")
puts table

Upvotes: 3

Boris Strandjev
Boris Strandjev

Reputation: 46963

Here is my code that tries to achieve what you want:

a = [["a", 1, 2 ,3], ["a", 1, 2 ,3], ["a", 1, 2 ,3],
     ["b", 1, 2 ,3], ["b", 1, 2 ,3], ["b", 1, 2 ,3], ["c", 1, 2 ,3]]
grouped = a.group_by{|t| t[0]}.values
header = "<tr><td>Name</td> <td>Length</td> <td>Width</td> <td>Depth</td> </tr>"
for portion in grouped
    str = "<table>\n" + header + "\n"
    for line in portion
        str += "<tr>"
        for element in line
            str += "<td>" + element.to_s + "</td>"
        end
        str += "</tr>\n"
    end
    str += "</table>\n"
    puts str
end

It is not the most beautiful ruby, but at least produces tables that look like that: enter image description here

Note that this is an image screen shot of an html in which I include the output tables. From now on you will need only to style them a bit.

Upvotes: 1

Related Questions