我认为这个问题已经打破了我的大脑。这就是我最终想要做到的:
mylibrary = [{:shelfa => ["booka", "bookb", "bookc"]}, {shelfb=> ["booka", "bookb"]}]
这就是我所拥有的:
class Library
def initialize
#create library array
@library = Array.new
end
def add_shelf(shelf_name)
#create shelf hash ({:shelfa => []}
@shelf_name = Shelf.new
#add shelf hash to library array
@library << @shelf
end
end
class Shelf
attr_accessor: shelf_name
def initialize
#create shelf hash {:shelfa => []}
@shelf = Hash.new{|shelf_name, book_array| shelf_name[book_array] = []}
end
end
这应该让我明白:
mylibrary = {:shelfa => [], shelfb: => []}
但是现在我需要第三个类Book,它将创建一本书并将其放在给定的书架上,即将标题推送到相应书架键的值数组中。这就是我所拥有的:
class Book
attr_accessor :title, :shelf_name
def initialize(title, shelf_name)
@title = title
@shelf_name = shelf_name
end
def add_book(title, shelf_name)
#push titles to empty array in the hash with key shelf_name
end
end
有任何想法吗?我不知道这种解释是否有意义,如果您有问题,我可以尝试更好地解释。谢谢!