I have an array of sub-arrays like this
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", nil]]
How can I iterate over this to create an html table whose sub-array is a column of the table as below?
a d g
b e h
c f
I have an array of sub-arrays like this
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", nil]]
How can I iterate over this to create an html table whose sub-array is a column of the table as below?
a d g
b e h
c f
It is your lucky day, ruby has just the thing for you, Array#transpose.
ary = [["a", "b", "c"], ["d", "e", "f"], ["g", "h", nil]]
ary.transpose.each {|a| p a }
# >> ["a", "d", "g"]
# >> ["b", "e", "h"]
# >> ["c", "f", nil]
zip, though had never heard of transpose :) Great answer, and a good one to know about. +1I think this does what you're after:
zipper = array.shift
puts zipper.zip(*array).map { |sub_array| sub_array.join(' ') }
So, you take the first element of the array and assign to a variable (zipper in this case).
You then zip the other arguments into this, and join them with a space as a separator.
Or, in one line:
array.shift.zip(*array)
When this is printed to the console, you get the output desired.
zipper, btw. You don't use it separately. array.shift.zip(*array).map ...As per the given description it seems like the below mentioned solution could work:
array.each do |f|
<tr> # this will be row
f.each do |g|
<th>g</th> # this will be column
end
</tr>
end