原谅人为的例子,如果我有......
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
的情况下做到这一点。
答案 0 :(得分:2)
可能是:
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)