2

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  
2
  • Will the sub arrays always be of equal length? Commented Jul 12, 2018 at 15:04
  • 1
    yes, they will always be equal length and will include nils to fill in Commented Jul 12, 2018 at 15:08

3 Answers 3

4

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]
Sign up to request clarification or add additional context in comments.

3 Comments

I was happy with my use of zip, though had never heard of transpose :) Great answer, and a good one to know about. +1
@SRack In my 12 years of doing ruby I have used transpose maybe 5 times. 4 of those were stackoverflow answers :)
Great solution ! You could maybe incorporate @Rohan 's solution for a complete answer though
2

I 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.

1 Comment

You can inline zipper, btw. You don't use it separately. array.shift.zip(*array).map ...
0

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

4 Comments

This prints arrays as rows, not columns.
second loop will print it as columns
No, it won't. It will print them as cells in a row.
You're producing a transposed matrix of the expected results, it needs to print the first element of each sub array, then in a new row it needs to print the second element of each sub array and so on

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.