2012-07-29 86 views
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明確。

回答

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) 
+0

感謝;現在看來很明顯。 :) – neezer 2012-07-29 20:05:18