ruby - NameError:未初始化的常量 Song ...Programming Ruby

标签 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 

我看到我需要 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/

相关文章:

ruby 流量控制

java - 从 VB.Net 执行 Java 类

python - NameError:名称未在 python init 函数中定义

来自变量内容的 Python NameError

python-2.7 - Python : Can't import a function from another. py 文件

ruby - github 帖子是否可以有多个命名约定?

ruby - 我很困惑,在 OS X 上安装 Ruby 1.9.2 最简单的方法是什么?

带有外部库的 C++ Ruby 扩展

iphone - Objective-C : Accessing constants from other classes

java - 使用简单的打印方法打印数组对象