views:

55

answers:

1

Is it possible to transpose an html table (without javascript). I m generating a table with rails (and erb) from a list of object. So it's really easy and natural to do it when each row correspond to one object. However , I need each object to be represented as a column. I would like to have only one loop and describe each column rather than doing the same loop for every columns. (That doesn't necessarily needs to be a real table , could be a list or anything which does the trick).

update

To clarify the question. I don't want to transpose an array in ruby, but to display a html table with the row vertically. My actual table is actually using one partial per row, wich generate a list of cell (td). That can be change to a list if that help. Anyway this is HTML question not a ruby one : how to display a table with the rows vertically (rather than horizontally).

A: 

You may need something like this?

class Array
  def transpose
    # Check here if self is transposable (e.g. array of hashes)
    b = Hash.new
    self.each_index {|i| self[i].each {|j, a_ij| b[j] ||= Array.new; b[j][i] = a_ij}}
    return b
  end
end

a = [{:a => 1, :b => 2, :c => 3}, {:a => 4, :b => 5, :c => 6}]
a.transpose #=> {:a=>[1, 4], :b=>[2, 5], :c=>[3, 6]}
Alberto
I don't need ruby code , see my update.
mb14