2016-05-27 16 views
0

Ich habe eine undefinierte Methode.Nicht definierte Methode `<< 'für Null: NilClass (NoMethodError)

rb:31:in `add_song': undefined method `<<' for nil:NilClass (NoMethodError) 

Ich verstehe, dass @library[artist] gibt nil, aber ich verstehe nicht, warum und weiß nicht, wie es zu beheben. Irgendein Rat?

module Promptable 
    def prompt(message = "What music would you like to add", symbol = ":>") 
    print message 
    print symbol 
    gets.chomp 
    end 
end 


class Library 
    attr_accessor :artist, :song 
    def initialize 
    @library = {} 
    end 

    def add_artist(artist) 
    @library[artist] = [] 
    end 

    def add_song(song) 
    @library[artist] << song 
    end 

    def show 
    puts @library 
    end 
end 

class Artist 
    attr_accessor :name, :song 

    def initialize(artist) 
    @name = artist[:name] 
    @song = artist[:song] 
    end 

    def to_s 
    "#{name}, #{song}" 
    end 
end 


if __FILE__ == $PROGRAM_NAME 
    include Promptable 
    include Menu 
    my_library = Library.new 
    my_library.add_artist(Artist.new(:name => prompt("What it the artist name ?"))) 
    my_library.add_song(Artist.new(:song => prompt("What is the song name ?"))) 
    my_library.show 
end 

Antwort

2

Du nennst add_artist mit einer Instanz von Artist und add_song mit einem anderen. Wenn Sie die Liste der Songs des Interpreten in mit @library[artist] nachschlagen, verwenden Sie einen Hash-Schlüssel (die zweite Instanz von Artist), der nicht dem Hash-Schlüssel entspricht, unter dem Sie die Liste gespeichert haben (die erste Instanz von Artist) Du bekommst die Liste nicht zurück, aber nil.

Um zwei verschiedene Instanzen von Artist als äquivalente Hash-Schlüssel zu verwenden, müssen Sie entscheiden, wann zwei Instanzen von Artist gleich sein sollen und implement eql? and hash appropriately.

Verwandte Themen