Ruby 从复杂方法链中获取父实例化对象?
原谅这个做作的例子,如果我有Ruby 从复杂方法链中获取父实例化对象?,ruby,class,object,Ruby,Class,Object,原谅这个做作的例子,如果我有 class Condiment def ketchup(quantity) puts "adding #{quantity} of ketchup!" end end class OverpricedStadiumSnack def add Condiment.new end end hotdog = OverpricedStadiumSnack.new 。。。调用hotdog.add.ketchup('tons!)时,是否仍然
class Condiment
def ketchup(quantity)
puts "adding #{quantity} of ketchup!"
end
end
class OverpricedStadiumSnack
def add
Condiment.new
end
end
hotdog = OverpricedStadiumSnack.new
。。。调用hotdog.add.ketchup('tons!)
时,是否仍然可以从调味品#番茄酱
中访问热狗
实例化对象
到目前为止,我找到的唯一解决方案是显式地传入
hotdog
,如下所示:
class Condiment
def ketchup(quantity, snack)
puts "adding #{quantity} of ketchup to your #{snack.type}!"
end
end
class OverpricedStadiumSnack
attr_accessor :type
def add
Condiment.new
end
end
hotdog = OverpricedStadiumSnack.new
hotdog.type = 'hotdog'
# call with
hotdog.add.ketchup('tons!', hotdog)
。。。但我希望能够做到这一点,而不必显式地传递热狗。可能是:
class Condiment
def initialize(snack)
@snack = snack
end
def ketchup(quantity)
puts "adding #{quantity} of ketchup! to your #{@snack.type}"
end
end
class OverpricedStadiumSnack
attr_accessor :type
def add
Condiment.new(self)
end
end
hotdog = OverpricedStadiumSnack.new
hotdog.type = 'hotdog'
hotdog.add.ketchup(1)
谢谢现在似乎很明显