Rails Solution
In rails, you can simply:
ary = [0,1,2,3,4,5,6,7,8,9] ary.in_groups_of(4).transpose.map(&:compact)
Explanation:
in_groups_of is a cool rail method added to the Array class, which is very similar to each_slice , with the difference that it ensures that all arrays are the same size. It is important here, so we can use transpose later. This method returns an array of your strings.
Now transpose is another cool method to know. It expects an array of arrays, and all internal arrays should be the same length (so in fact this is a rectangular matrix). What it does is it returns an array of columns in the target array.
Now we need to get rid of nils (if they do not bother you), so we run compact in each column, and we have exactly what you wanted.
Pure ruby โโsolution:
We do not have in_groups_of , so we need to implement the same behavior without it:
ary.each_slice(4).map {|a| a.fill nil, a.size, 4 - a.size}.transpose.map(&:compact)
The best solution to a practical problem
In practice, I would look at iterating over the active array of records, showing these (they are image records) in 4 different html columns, while preserving the order from left to right
You should never use tables to display your data unless it is tabular data. Images are not tabular data, which means that the location of this particular image in a given column / row is completely irrelevant. There is always a better way to do this.
In your case, I would suggest a pure CSS solution (haml):
%ul.images - @images.each do |i| %li= image_tag i.iamge_url
Then in your css (scss):
ul.images { width: 100%; font-size: 0;
The main advantage of this model is that you can specify the number of columns depending on media queries, so display a different number of images per row depending on the user's screen size (important for mobile phones).
If you feel more adventurous, and you hate IE and don't care about it, go in and check out the flexible boxes. Once it can become a standard and can already be seen on many pages.