我不确定为什么我的代码不会通过相应的测试。每次我尝试代码时,都会报告以下错误:“rb:60:in <main>': undefined local variable or method
track”for main:Object(NameError)。“如果不编辑测试,我该怎么办?谢谢!打开另一种方法......谢谢!
强文
class Song
attr_reader :song
def initialize(song, artist)
@song = song
@artist = artist
end
def play
puts "#{@song}by #{@artist}"
end
end
class Playlist
def initialize(player_list)
@player_list = player_list
end
def add(add_song)
add_song.each do |song|
@player_list << song
end
end
def track_number
@player_list.length
end
def remove(remove_song)
remove_song.each do |song|
@player_list.delete(song)
end
end
def includes?(from_list)
i = 0
from_list.each do |song|
if @player_list.include?(song)
i+=1
end
end
if i==from_list.length
true
else
false
end
end
def play_all
@player_list.each do |song|
song.play
end
end
def display
@player_list.each do |song|
puts song.song
end
end
end
one_by_one = Song.new("One by One", "Sirenia")
world_so_cold = Song.new("World So Cold", "Three Days Grace")
going_under = Song.new("Going Under", "Evanescence")
my_playlist = Playlist.new(one_by_one, world_so_cold, going_under)
lying_from_you = Song.new("Lying From You", "Linkin Park")
angels = Song.new("Angels", "Within Temptation")
my_playlist.add(lying_from_you, angels)
p my_playlist.track_number == 5
going_under.play
my_playlist.remove(angels)
p my_playlist.includes?(lying_from_you) == true
my_playlist.play_all
my_playlist.display
答案 0 :(得分:0)
当你为PlayList调用“add”方法时,它会期待一首歌曲。但是,“add”方法试图调用.each(),它可以用于一组歌曲但不能用于单首歌曲。
在不更改测试代码的情况下,最佳解决方案是删除“添加”,“删除”和“包含”中的“.each”调用。 PlayList的方法。让他们每次添加,删除或检查一首歌。