2014-06-10 13 views
0

我是一名新的Rubyist,並且想知道如何從單個cookie訪問配料類?衆所周知,餅乾由不同的原料製成。如何在不設置默認值的情況下指定單個Cookie的默認成分?即使我有默認值,我如何更新這些以反映最新的「配方」?請和謝謝!在Ruby中使用對象組合構建一個cookie

#Cookie Factory 

module CookieFactory 
    def self.create(args) 
    cookie_batch = [] 
    args.each do |cookie| 
     cookie_batch << PeanutButter.new if cookie == "peanut butter" 
     cookie_batch << ChocholateChip.new if cookie == "chocolate chip" 
     cookie_batch << Sugar.new if cookie == "sugar" 
    end 
    return cookie_batch 
    end 
end 

#Classes/Subclasses 

class Ingredients 
    attr_reader 
    def initialize(contents = {}) 
    # contents = defaults.merge(contents) 
    @sugar = contents.fetch(:sugar, "1.5 cups") 
    @salt = contents.fetch(:salt, "1 teaspoon") 
    @gluten = contents.fetch(:gluten, "0") 
    @cinnamon = contents.fetch(:cinnamon, "0.5 teaspoon") 
    end 
end 

class Cookie 
    attr_reader :status, :ingredients 

    def initialize(ingredients = {}) 
    @ingredients = ingredients 
    @status = :doughy 
    super() 
    end 

    def bake! 
    @status = :baked 
    end 

end 

class PeanutButter < Cookie 
    attr_reader :peanut_count 
    def initialize 
    @peanut_count = 100 
    super() 
    end 

    def defaults 
    { 
     :peanut_shells => 5 
    } 
    end 
end 

class Sugar < Cookie 
    attr_reader :sugar 
    def initialize 
    @sugar = "1_cup" 
    super() 
    end 
end 

class ChocholateChip < Cookie 
    attr_reader :choc_chip_count 
    def initialize 
    @choc_chip_count = 200 
    super() 
    end 
end 
+0

對於澄清:說我要初始化一個花生醬餅乾用的配料: 0.5杯黃油 1.0茶匙,花生油 如何我會添加並更新對象成分? – mendoncakr

回答

0

您可以使用Hash#merge來達致這行爲:

class PeanutButter < Cookie 
    attr_reader :peanut_count 
    def initialize(ingredients) 
    @peanut_count = 100 
    super(ingredients.merge(defaults)) 
    end 

    def defaults 
    { 
     :peanut_shells => 5 
    } 
    end 
end 
相關問題