Reputation: 2563
Imagine I have array of values ranging from 1 to 24. I want to populate these values in an HTML table as shown below.
HTML Table
| 1 | 2 | 3 | 4 | 5 | 6 |
| 7 | 8 | 9 | 10 | 11 | 12 |
| 13 | 14 | 15 | 16 | 17 | 18 |
| 19 | 20 | 21 | 22 | 23 | 24 |
Can anybody help me in figuring out how to loop through an array in ruby and populate these values? I am using ruby 1.8.7.
P.S Sorry about representing the HTML table in an ugly way.
Upvotes: 0
Views: 182
Reputation: 2563
This is more of an actual representation of what I exactly needed which is totally based on lucapette's answer. Thanks to him.
<table>
<% (1..24).each_slice(6).each do | num | %>
<tr>
<% num.each do |n| %>
<td> <%= n %></td>
<% end %>
</tr>
<% end %>
</table>
Upvotes: 0
Reputation: 20724
Use each_slice:
1.8.7 (main):0 > (1..24).each_slice(6).each {|b| p b }
[1, 2, 3, 4, 5, 6]
[7, 8, 9, 10, 11, 12]
[13, 14, 15, 16, 17, 18]
[19, 20, 21, 22, 23, 24]
Upvotes: 3