What's the best way to iterate over an array of arrays?
sounds = [ [Name_1, link_1], [Name_2, link_2], [Name_3, link_3], [Name_4, link_4] ]
I want to the output in html ul/li structure
- Name_1, link_1
- Name_2, link_2
- Name_3, link_3
- Name_4, link_4
What's the best way to iterate over an array of arrays?
sounds = [ [Name_1, link_1], [Name_2, link_2], [Name_3, link_3], [Name_4, link_4] ]
I want to the output in html ul/li structure
Use a nested loop. The outer one iterates over sounds, while the inner one iterates over the current element from sounds.
Of course, in that particular example, it would probably be easiest just to directly reference the elements of the inner arrays. That way, you could just print <li>$inner[0], $inner[1]</li>
(note that I've never used Ruby, so I don't know how arrays are indexed, let alone printing syntax).
In view:
<ul>
<% sounds.each do |sound| %>
<li> <%=h sound.join ', ' %></li>
<% end %>
</ul>
Assuming all the inner arrays have fixed size, you can use auto-unpacking to get each item of the inner array in its own variable when iterating over the outer array. Example:
sounds.each do |name, link|
# do something
end