在Ruby中用对象组合建模cookie
我是一个新的红宝石爱好者,我想知道如何从单个饼干中访问配料类?众所周知,饼干是由不同的成分制成的。如何在不设置默认值的情况下为单个cookie指定默认成分?即使我有默认值,我如何更新这些值以反映最新的“配方”?请,谢谢在Ruby中用对象组合建模cookie,ruby,oop,inheritance,Ruby,Oop,Inheritance,我是一个新的红宝石爱好者,我想知道如何从单个饼干中访问配料类?众所周知,饼干是由不同的成分制成的。如何在不设置默认值的情况下为单个cookie指定默认成分?即使我有默认值,我如何更新这些值以反映最新的“配方”?请,谢谢 #Cookie Factory module CookieFactory def self.create(args) cookie_batch = [] args.each do |cookie| cookie_batch <<
#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
#饼干工厂
模块Cookie工厂
定义自创建(args)
cookie\u批处理=[]
args.each do| cookie|
cookie_batch您可以使用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
class花生酱5
}
结束
结束
澄清:假设我想初始化一个花生酱饼干,其成分为:0.5杯黄油1.0茶匙花生油。我如何添加该成分并更新对象成分?