2013-06-24 146 views
0

我认为这个问题已经打破了我的大脑。这就是我最终设法使: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 

任何想法?我不知道这个解释是否有意义,如果你有问题,我可以更好地解释。谢谢!

+0

你真的不需要给货架命名吗?我没有看到任何 –

+0

为什么库是一个数组?或者是?你说它是两个。似乎更有意义的散列,'@library [shelf_name] = Shelf.new'。 'add_book'方法应该也可以放在货架类上。 – numbers1311407

+1

你对OOP的目的有一些严重的误解。您不应该构建三个类来包装单个分层数组。你还应该重新考虑你的名字:一个'Library'不包含一个名为'@ library'的货架,它应该包含一个叫做'@ shelf'的货架阵列。同样,'Shelf'不包含名为'@ shelf'的书籍,它应该包含'@ books'。 – meagar

回答

0

你已经有了一个明显的错字在你的代码,这将工作,但产生非常不好的结果:

首先,你初始化@shelf_name

#create shelf hash ({:shelfa => []} 
@shelf_name = Shelf.new 

然后,参考@shelf,这是nil

#add shelf hash to library array 
@library << @shelf 
0

除了一些明显的错别字/错误(一些我在下面更正),你的这个程序的逻辑似乎是关闭的。举一个例子,图书馆也会更有意义。其次,你不能有一个方法add_book里面的Book类;书籍被添加到图书馆。 Book应该只包含有关Book本身的信息:名称,作者,流派等..

class Library 
    def initialize 
    #create library array 
    @library = [] 
    end 

    def add_shelf(shelf_name) 
    #create shelf hash ({:shelfa => []} 
    @shelf = Shelf.new shelf_name 

    #add shelf hash to library array 
    @library << @shelf 
    end 

    def add_book(book, shelf_name) 
    # your code here 
    end 
end 

class Shelf 
    attr_accessor :shelf_name, :shelf 

    def initialize shelf_name 
    @shelf_name = shelf_name 

    #create shelf hash {:shelfa => []} 
    @shelf = { shelf_name => [] } 
    end 
end 
0

所以......

@library[shelf_name] << title 

...好像明显的答案。

相关问题