2011-12-20 9 views
0

클래스 Bar1, Bar2, Bar3의 인스턴스 변수가있는 클래스가 있다고합시다. Bar 클래스 정의는 임의적이며 예를 들어 이름이 비슷합니다.매개 변수 중 하나를 통해 객체 참조

class Foo 
    attr_reader :test_value 

    def initialize 
    @test_value = "awesome" 
    @bar1 = Bar1.new 
    @bar2 = Bar2.new 
    @bar3 = Bar3.new 
    end 
end 

BAR1, BAR2, 왈져가 난 그냥 데모를 위해 소유자 값을 만들어

class Bar1 
    def initialize 
    @value = owner.test_value # 'owner' would refer the Foo instance that contains this Bar1 
    end 
end 

class Bar2 
    def initialize 
    @value = owner.test_value 
    end 
end 

class Bar3 
    def initialize 
    @value = owner.test_value 
    end 
end 

로 정의되는 경우,이 경우에도 가능한 같은입니까? 이것은 스트레치처럼 보입니다. 아마도이 기능을 요구하는 코드를 재구성하면 해결할 수 있지만, 완전히 포기하기 전에 가능한지 알고 싶습니다.

감사합니다.

답변

1
class Foo 
    attr_reader :test_value 

    def initialize 
    @test_value = "awesome" 
    @bar1 = Bar1.new(self) 
    @bar2 = Bar2.new(self) 
    @bar3 = Bar3.new(self) 
    end 
end 

class Bar1 
    def initialize owner 
    @value = owner.test_value 
    end 
end 

class Bar2 
    def initialize owner 
    @value = owner.test_value 
    end 
end 

class Bar3 
    def initialize owner 
    @value = owner.test_value 
    end 
end 
+0

). 실제로 원하는 경우 해당 소유자에 대한 참조를 보유 할 수도 있습니다. 'initialize'에'@owner = owner'라는 줄을 추가하기 만하면됩니다. Ruby 객체가 다른 객체를 참조 할 수있는 규칙은 없습니다. 그것은 물체가 나무 같은 것을 형성하는 것과 같지 않습니다. –

+0

이것은 잘 작동하지만, 프로그래밍의 긴 하루가 지나면 이것을 수행하지 못했습니다. 감사합니다! –

0

개체는 천 가지의 다른 변수에 동시에 할당 될 수 있기 때문에 "소유자"가 무엇인지 알 수 없습니다. 유일한 근사값은 개체를 만들 때 인스턴스 변수를 명시 적으로 설정 한 경우입니다 (예 :

def Foo 
    attr_reader :test_value, :bar1 

    def initialize 
    @test_value = 'awesome' 

    @bar1 = Bar1.new 
    @bar1.owner = self # you could also make Bar1#new take an argument which 
    end     # would be assigned to @owner 
end 

def Bar1 
    attr_accessor :owner 

    def initialize 
    # ... 
    end 

    def value 
    owner.test_value 
    end 
end 

f = Foo.new 
f.bar1.value # => 'awesome' 
+0

위의 대답과 같은 개념이지만 입력 해 주셔서 감사합니다. –

관련 문제