Skip to content

Instantly share code, notes, and snippets.

@pduey
Created April 16, 2012 16:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pduey/2399822 to your computer and use it in GitHub Desktop.
Save pduey/2399822 to your computer and use it in GitHub Desktop.
Ruby on Rails Tabular Data Ordered Column-wise
class Array
# Converts a one dimensional array into a table with the given number of columns. Optionally transposes
# the result. Suited for output to an HTML table you want sorted vertically instead of horizontally.
# Pads correctly, i.e., each row/column has at most one empty cell. num_columns is the desired number
# of columns in the result, regardless if the table is transposed.
def tabulate(num_columns, transpose=true)
if transpose
num_rows = num_columns
num_columns = ((self.size - 1) / num_columns) + 1
else
num_rows = ((self.size - 1) / num_columns) + 1
end
num_rows_to_pad = self.size % num_columns > 0 ? num_rows - (num_columns - self.size % num_columns) : 0
tabulated = []
a_register = []
# TODO: do this in chunks, not one element at a time
self.each_with_index do |element, i|
if a_register.size == num_columns - 1
if num_rows_to_pad > 0 && tabulated.size + 1 > num_rows_to_pad
a_register << nil
tabulated << a_register
a_register = []
a_register << element
else
a_register << element
tabulated << a_register
a_register = []
end
else
a_register << element
end
end
if num_rows_to_pad > 0 && a_register.size < num_columns
a_register << nil
tabulated << a_register
end
if transpose
tabulated.transpose
else
tabulated
end
end
end
<%# Example: turns [a, b, c, d, e, f, g, h, i, j] into %>
<%# [[a, b, c, d], [e, f, g, nil], [h, i, j, nil]] then transposes that into %>
<%# [[a, e, h], [b, f, i], [d, nil, nil]] for easy html table output into: %>
<%# a e h %>
<%# b f i %>
<%# c g j %>
<%# d %>
<%# note: in this example, i've added tabulate as method to Array class %>
<table>
<% ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j"].tabulate(3, true).each do |row| %>
<tr>
<% row.each do |element| %>
<td><%= element</td>
<% end %>
</tr>
<% end %>
</table>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment