我认为这个问题已经打破了我的大脑。这就是我最终设法使:Ruby:创建一个哈希数组,其中每个值都是一个数组
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
任何想法?我不知道这个解释是否有意义,如果你有问题,我可以更好地解释。谢谢!
你真的不需要给货架命名吗?我没有看到任何 –
为什么库是一个数组?或者是?你说它是两个。似乎更有意义的散列,'@library [shelf_name] = Shelf.new'。 'add_book'方法应该也可以放在货架类上。 – numbers1311407
你对OOP的目的有一些严重的误解。您不应该构建三个类来包装单个分层数组。你还应该重新考虑你的名字:一个'Library'不包含一个名为'@ library'的货架,它应该包含一个叫做'@ shelf'的货架阵列。同样,'Shelf'不包含名为'@ shelf'的书籍,它应该包含'@ books'。 – meagar