我正在尝试获取albums.title(在display_album方法中)。每当我通过终端运行代码时,它都会为#表示未定义的方法“ title”。我认为我正确放置了所有实例。我不确定我想念什么。
我试图检查是否正确放置了实例,并且还尝试使用p方法进行调试以检查实例变量在整个类中是否不起作用。
$genre = ['Null', 'Pop', 'Classic', 'Jazz', 'Rock']
class Album
attr_accessor :title, :artist, :genre, :tracks
def initialize(title, artist, genre, tracks)
@title = title
@artist = artist
@genre = genre
@tracks = tracks
end
end
def read_albums()
puts "write a file name"
afile = gets.chomp
file = File.new(afile, "r")
albums = Array.new()
if file
i =0
count = file.gets.to_i
while i<count
albums << read_album(file)
i +=1
end
file.close
end
albums
end
def read_album(file)
album_title = file.gets
album_artist = file.gets
album_genre = file.gets
album_tracks = read_tracks(file)
album = Album.new(album_title, album_artist, album_genre, album_tracks)
album
end
def display_albums(albums)
finished = false
begin
selection = read_integer_in_range("choose the number", 1, 3)
case selection
when 1
display_album(albums)
when 2
display_genres
when 3
finished = read_boolean 'Are you sure to exit ? (enter yes if yes)'
else
puts 'Please select again'
end
end
end
def display_album(albums)
puts "the album title is" + albums.title.to_s
end
def main_menu
finished = false
begin
selection = read_integer_in_range('please select the number between 1 and 5', 1, 5)
case selection
when 1
albums = read_albums
when 2
display_albums(albums)
when 3
play_album
when 4
update_album
when 5
finished = read_boolean 'Are you sure to exit ? (enter yes if yes)'
else
puts 'Please select again'
end
end until finished
end
main_menu
我希望获得一个标题名称,即“ Coldplay Viva la Vida或Death and All His Friends”。
我收到的错误消息是music_player.rb:103:display_album': undefined method
标题中的#(NoMethodError)
答案 0 :(得分:0)
def display_album(albums)
puts "the album title is" + albums.title.to_s
end
您要输入一系列相册,而不是一个单独的相册。更改为:
def display_album(album)
puts "the album title is" + album.title.to_s
end
当调用该方法时,请确保仅使用一个专辑作为参数而不是数组来调用它。错误是告诉您您只需要在一个项目上调用一个专辑数组时就调用“ title”方法。