class Books
attr_accessor :name, :book_id
def initialize(name, book_id)
@name = name,
@book_id = book_id
end
end
class BookCollection
def intialize
@book_names = []
end
def add_to_books(book_name)
book_name.push(book_names)
end
end
book1 = Books.new("catch22", "12345")
book_collection1 = BookCollection.new
book_collection1.add_to_books(book1.name)
puts book_collection1
端
这是我的代码,我得到的错误是“未定义的局部变量或方法`book_names'”。我尝试添加“attr_accessor:book_names”,当我这样做时,打印输出没有意义。
答案 0 :(得分:0)
可能只是一个错字
book_name.push(book_names)
应该是
book_names.push(book_name)
使用attr_accessor :book_names
答案 1 :(得分:0)
您的代码中存在一些错误:
initialize
中的{li> class BookCollection
拼写错误,导致@book_names
未初始化。因此,当您尝试使用@book_names
向其添加元素时,nil
等于push
。 nil
没有方法push
;因此异常,以及打印有异常的消息。
book_name.push(book_names)
应为@book_name.push(book_name)
。 (@book_name
必须是一个instance_variable,而不是局部变量,在类定义中可以在方法外看到。puts book_collection1
打印类实例;您想要打印@book_names
。我在这里修复了你的代码。我使用<<
代替push
。要么是好的,但前者似乎最受青睐。
class Books
attr_accessor :name, :book_id
def initialize(name, book_id)
puts "name = #{name}, book_id = #{book_id}"
@name = name
@book_id = book_id
end
end
class BookCollection
attr :book_names
def initialize
@book_names = []
end
def add_to_books(book_name)
@book_names << book_name
end
end
book_collection1 = BookCollection.new
book1 = Books.new("Catch22", "12345")
book2 = Books.new("Hawaii", "67890")
book_collection1.add_to_books(book1.name)
book_collection1.add_to_books(book2.name)
book_collection1.book_names # => ["Catch22", "Hawaii"]