首页 > 解决方案 > 为什么我得到未定义的方法“标题”#(无方法错误)?

问题描述

我正在尝试获取 albums.title (在 display_album 方法中)。每当我通过终端运行代码时,它都会显示为 # 取消定义方法“标题”。我想我正确地放置了所有实例。我不确定我想念什么。

我试图检查我是否正确放置了实例,并使用 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 or Death and All His Friends”。

我收到的错误消息是 music_player.rb:103:in display_album': undefined methodtitle' for # (NoMethodError)

标签: ruby

解决方案


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

当您调用该方法时,请确保仅使用一张专辑作为参数而不是数组来调用它。该错误告诉您您正在对一组专辑调用“标题”方法,而您只需要在一个项目上调用它。


推荐阅读