2012-07-29 6 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

관련 문제