ruby - 为什么我得到未定义的方法“标题”#(无方法错误)?
问题描述
我正在尝试获取 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 method
title' for # (NoMethodError)
解决方案
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
当您调用该方法时,请确保仅使用一张专辑作为参数而不是数组来调用它。该错误告诉您您正在对一组专辑调用“标题”方法,而您只需要在一个项目上调用它。
推荐阅读
- google-chrome - 如何找出 Google Sheet 查询 #N/A 错误(仅在打开时)
- artificial-intelligence - 如何确定水壶问题的 A* 算法的成本和启发式算法
- amazon-dynamodb - 具有低基数分区键的 DynamoDB 全局二级索引是否有大小限制?
- c# - 将渲染器的所有材质更改为一种材质
- regression - 使用比例的 metafor 包中的 R 元回归气泡图
- amazon-redshift - AWS Redshift - 身份字段语法
- asp.net - XmlException:根级别的数据无效。第 1 行,位置 1
- azure-devops - TFS Undo 将团队项目转换为分支
- apache-spark - 通过 ingress 访问所有 kubernetes statefulset pod
- javascript - 返回一个带有创建它的函数的对象作为方法