未定义的方法`<<' for nil:NilClass(NoMethodError)

时间:2016-05-27 16:34:52

标签: ruby

我有一个未定义的方法。

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

我确实理解@library[artist]给出了nil,但我不明白为什么,也不知道如何修复它。有什么建议吗?

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

1 个答案:

答案 0 :(得分:2)

您正在使用add_artistArtist的一个实例与另一个实例调用add_song。当您使用add_song@library[artist]中查找艺术家的歌曲列表时,您使用的哈希键(Artist的第二个实例)不等同于存储列表的哈希键(Artist的第一个实例),因此您无法返回列表,但nil

要将Artist的两个不同实例用作等效哈希键,您需要确定两个Artist实例何时应该相等且implement eql? and hash appropriately