Home > Enterprise >  Is there a way to loop something multiple times specifically
Is there a way to loop something multiple times specifically

Time:10-26

I have

def read_album(music_file)
  music_file.gets
  album_artist = music_file.gets
  album_title = music_file.gets
  album_genre = music_file.gets.to_i
  tracks = read_tracks(music_file)
  album = Album.new(album_artist, album_title, album_genre, tracks)
  print_album(album)
end

I want to loop the entire block 3 times (maybe use something like 3.times do), but have music_file.gets (the first line in the procedure) run a different amount of times per loop. (say just once on the first loop, 5 times on the second loop, 8 times on the third loop.) I'm not sure if there's a way to add an index and somehow have the index change from specific values per loop and have music_file.gets repeat according to that, or some other way.

Edit: the text file has a group of albums and has a format similar to this: I want to use the number of tracks as a control variable for a loop to read the album info, music_file.gets is to get that info.

Albums.txt (the file name, everything below is a separate line of text in the file)
*Number of albums (integer)
*Artist name
*Album name
*Number of Tracks (integer)
*Track 1
*Track 2
*Artist Name
*Album name
*Number of Tracks (integer)
*Track 1
*Track 2
*Track 3
etc. (number of tracks per album are random)

CodePudding user response:

Given a pair of counts acquired by reading, you could use a nested loop structure. Two basic mechanisms for counts are count.times or Range.each, illustrated here:

number_of_albums.times do |i|    # i goes from 0 to m-1
  # do album stuff, including picking up the value of number_of_tracks
  (1..number_of_tracks).each do |j|    # j goes from 1 to number_of_tracks
    # do track stuff
  end
  # do additional stuff if needed
end

If the "stuff" to be done is a one-liner, you can replace do/end with curly braces.

See this tutorial for much more information about the variety of looping options.

  • Related