2014-06-13 98 views
1

試圖通過這種編程紅寶石網站拿起紅寶石,我被困在這句法NameError:未初始化的常量歌...編程紅寶石

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 

我看到了,我需要導入該變量歌,但我不知道wher e將的SongList類中做....

+4

你需要創建一個'Song'類。 –

+0

看起來他們可能使用了[本教程]的一些變體(http://phrogz.net/programmingruby/frameset.html),它具有類定義。 –

回答

3

您可以使用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>]> 
相關問題