2011-04-28 4 views
1

이것은 아마도 이미 대답 해 왔지만 보드 검색을 사용하여 해결책을 찾기에는 적절한 어휘가 부족합니다.Ruby 클래스의 다른 클래스에 대한 이야기 ​​

내가 습득하고자하는 것은 다른 클래스의 클래스 인스턴스의 메서드를 호출하는 것입니다.

나는이 원유 예를 들어 내가 acheive 원하는 것을 보여 생각 :

class ClassA 
    def method_a 
    return 'first example' 
    end 

    def method_b 
    return 'second example' 
    end 
end 

class ClassB 
    def initialize 
    object = classA.new 
    end 
end 

the_example = classB.new 
the_example.[whatever-I’m-missing-to-talk-with-object].method_b 
# should return 'second exampe' 
+0

'classA'가 소문자로 시작하기 때문에 코드 샘플이 실행되지 않습니다. 스택 오버플로에 게시하기 전에 IRB에서 코드를 실행하고 싶을 수 있습니다. –

답변

2

object 요구가 initialize를 호출 한 후 범위를 벗어나하지 않도록 인스턴스 변수로, 그래서 @object를 호출 대신.

그런 다음 classB의 정의를 벗어난 곳에서 @object에 액세스 할 수 있도록 설정해야하므로이를 선언해야합니다. the_examplemethod_b 전화를받을 때

require "forwardable" 

class ClassB 
    extend Forwardable 
    def_delegators :@object, :method_b 

    def initialize 
    @object = ClassA.new 
    end 
end 

그런 식으로, 그것은 @object.method_b의 결과를 반환하여, 그것을 위임 할 알고 :

class ClassB 
    attr_reader :object # lets you call 'some_instance_of_classb.object' 
    def initialize 
    @object = ClassA.new 
    end 
end 
+0

Spot on. 고맙습니다! – Aeyoun

2

오히려 @object 변수를 노출하는 것보다, 당신은 위임자를 사용할 수 있습니다.

관련 문제