1
原諒了人爲的例子,如果我有...從複雜方法鏈中獲取父實例化對象?
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!')
時從Condiment#ketchup
內獲得訪問hotdog
實例化的對象?
到目前爲止,我已經找到了唯一的解決辦法是通過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
明確。
感謝;現在看來很明顯。 :) – neezer 2012-07-29 20:05:18