[英]Ruby how to loop the two objects at the same time
While I do @songs.each当我做@songs.each
I'd like to do @artist.each at the same time.我想同时做@artist.each。
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.如果艺术家在歌曲 object 中给出。
You could create a hashmap of songlists.您可以创建一个 hashmap 的歌曲列表。 So you need only one songs loop.所以你只需要一个歌曲循环。
https://ruby-doc.org/core-2.7.1/Hash.html 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:您可以使用Array#zip
将 arrays 组合成一个具有嵌套值的数组并遍历该列表:
<% @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 %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.