简体   繁体   中英

Ruby how to loop the two objects at the same time

While I do @songs.each
I'd like to do @artist.each at the same time.
So I can make the list.

<% @songs.each do |song|  %>
      <p class="list-group-item"><%= truncate(song.to_s, length: 10) %></p>
<% end %>

<% @artists.each do |artist| a%>
<p class="list-group-item"><%= truncate(aritst.to_s, length: 10) %></p>

Assuming you want to have a list of songs for each artist:

If the artist is given in the song object.

You could create a hashmap of songlists. So you need only one songs loop.

https://ruby-doc.org/core-2.7.1/Hash.html

Something like:

songlists = {}
songs.each do |song|
   unless songlists.has_key?(song.artist)
      songlists[song.artist] = []
   end

   songlists[song.artist].push(song)
end

You can use Array#zip to combine both arrays into one array with nested values and the iterate through that list:

<% @songs.zip(@artists).each do |(song, artist)|  %>
  <p class="list-group-item"><%= truncate(song.to_s, length: 10) %></p>
  <p class="list-group-item"><%= truncate(aritst.to_s, length: 10) %></p>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM