【问题标题】:NameError: uninitialized constant Song ...Programming RubyNameError: uninitialized constant Song ...Programming Ruby
【发布时间】:2014-06-13 19:55:13
【问题描述】:

试图通过这个编程 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 类中的什么位置......

【问题讨论】:

  • 你需要创建一个Song类。
  • 看起来他们可能正在使用具有类定义的this tutorial 的某些变体。

标签: ruby class nameerror


【解决方案1】:

您可以使用 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>]>

【讨论】:

    猜你喜欢
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多