Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to iterate over an array of arrays

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:

<ul>
   <li>Name_1, link_1</li>
   <li>Name_2, link_2</li>
   <li>Name_3, link_3</li>
   <li>Name_4, link_4</li>
</ul>

2 Answers

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
like image 170
sepp2k Avatar answered Sep 13 '25 06:09

sepp2k


In view:

<ul>
  <% sounds.each do |sound| %>
    <li> <%=h sound.join ', ' %></li>
  <% end %>
</ul>
like image 38
klew Avatar answered Sep 13 '25 07:09

klew