试图通过这个编程 ruby 站点获取 ruby,但我被这个语法困住了
class SongList
def initialize
@songs = Array.new
end
def append(aSong)
@songs.push(aSong)
self
end
def deleteFirst
@songs.shift
end
def deleteLast
@songs.pop
end
end
当我去添加一首歌时...
list = SongList.new
list.append(Song.new('title1', 'artist1', 1))
我收到此错误消息:
NameError: uninitialized constant Song ...Programming Ruby
我看到我需要 require 变量 Song,但我不确定在 SongList 类中的什么地方做它....
最佳答案
您可以使用 ruby Struct
类:
A
Struct
is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class.
class SongList
def initialize
@songs = [] # use [] instead of Array.new
end
def append(aSong)
@songs.push(aSong)
self
end
def delete_first
@songs.shift
end
def delete_last
@songs.pop
end
end
Song = Struct.new(:song_name, :singer, :var)
list = SongList.new
list.append(Song.new('title1', 'artist1', 1))
# => #<SongList:0x9763870
# @songs=[#<struct Song song_name="title1", singer="artist1", var=1>]> var=1>]>
关于ruby - NameError:未初始化的常量 Song ...Programming Ruby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24212959/