There are a few mistakes in your code:
- line 4 should not end with a comma.
initialize in class BookCollection is misspelled, resulting in @book_names not being initialized. @book_names therefore equals nil when you attempt to add an element to it with push. nil does not have a method push; hence the exception, and the message printed with the exception.
book_name.push(book_names) should be @book_name.push(book_name). (@book_name must be an instance_variable, as opposed to a local variable, to be visible outside a method, within the class definition.
puts book_collection1 prints the class instance; you want to print @book_names.
Here I've fixed your code. I've used << instead of push. Either is OK, but the former seems to be favored my most.
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"]
@book_names.push(book_name)? Also, instead ofputs book_collectionyou need a method (e.g.,attr_reader) to return @book_names.