NameError:uninitialized constant Song ...编程Ruby

时间:2014-06-13 19:55:13

标签: ruby class nameerror

尝试通过这个编程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 

我看到我需要变量Song,但我不确定在SongList类中的位置....

1 个答案:

答案 0 :(得分:3)

您可以使用Ruby Struct类:

  

Struct是一种使用访问器方法将多个属性捆绑在一起的便捷方式,而无需编写显式类。

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>]>