原谅我设计的例子,如果我有.
class Condiment
def ketchup(quantity)
puts "adding #{quantity} of ketchup!"
end
end
class OverpricedStadiumSnack
def add
Condiment.new
end
end
hotdog = OverpricedStadiumSnack.new..。在调用hotdog时,是否可以从Condiment#ketchup内部访问实例化的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)..。但是,我希望能够在不显式传递hotdog的情况下做到这一点。
发布于 2012-07-29 06:52:47
可能是:
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)https://stackoverflow.com/questions/11707245
复制相似问题