使用数组元素完成迭代后重置计数器



我正在做这段代码,但在迭代数组中的所有元素后,我找不到重置计数器的正确方法。

这个想法是,在进入播放列表中的最后一首歌曲后,您将进入第一首歌曲。这是我的代码,非常感谢您的帮助。提前感谢!

class Playlist
attr_accessor :songs
def initialize (name,songs)
@name = name
@songs = songs
end
def display_name
@name
end
def number_of_songs
"There are #{@songs.count} songs in the #{display_name}"
end
def add_song(song)
@songs << song
@songs
end
def next_song
i = 0
while i != 9
p "Playing song: #{@songs[i]}"
p "skip song? (Y/N)"
user_input = gets.chomp
if user_input.downcase == "y" && i != 8
i += 1
elsif user_input.downcase == "n" && i != 8
puts "Playing song"
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
print'.'
puts
puts
i+=1
end
end
end
end
playlist = Playlist.new("The Ultimate Playlist",["In My Life","Naive","She Moves In Her Own Way","Skinny Love","All My Life","All The Small Things","Real"])
p playlist.display_name
p playlist.number_of_songs
p playlist.add_song("California(Here We Come)")
puts
p playlist.next_song

上课后,我找到了解决这个问题的方法。 这很容易实现,但我知道有更好的选择来解决问题。 谢谢大家的帮助!:D

PD:如果您愿意,请评论您找到的其他解决方案

class Playlist
attr_accessor :songs
def initialize (name,songs)
@name = name
@songs = songs
end
def display_name
@name
end
def number_of_songs
"There are #{@songs.count} songs in the #{display_name}"
end
def add_song(song)
@songs << song
@songs
end
def next_song
max =@songs.length
i = 0
finish = ""
puts "Write Play to start the playlist (#{@name})"
puts
promt =">"
print promt
while finish.downcase != "play"
finish = gets.chomp
i = 0
puts
while i <max
p "Playing song: #{@songs[i]}"
p "skip song? (Y/N) or exit to end the playlist"
print promt
user_input = gets.chomp
if user_input.downcase == "y" && i != 8
i += 1
elsif user_input.downcase == "n" && i != 8
puts "Playing song"
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
sleep(1)
print'.'
sleep(1)
print'.'
sleep(1)
print'.'
puts
puts
i+=1
elsif user_input.downcase == "exit"
exit!
end
end
puts
p "Restarting playlist"
puts
puts "Write Play to start the playlist (#{@name})"
puts
end 
end
end
playlist = Playlist.new("The Ultimate Playlist",["In My Life","Naive","She Moves In Her Own Way","Skinny Love","All My Life","All The Small Things","Real"])
p playlist.display_name
p playlist.number_of_songs
p playlist.add_song("California(Here We Come)")
puts
p playlist.next_song

最新更新