2009-08-09 2 views
47
 
class A 
    def a 
    puts 'in #a' 
    end 
end 

class B < A 
    def a 
    b() 
    end 
    def b 
    # here i want to call A#a. 
    end 
end 

답변

79
class B < A 

    alias :super_a :a 

    def a 
    b() 
    end 
    def b 
    super_a() 
    end 
end 
+0

클래스 메소드의 별명 지정 방법은 http://stackoverflow.com/questions/2925016/alias-method-and-class-methods-dont-mix –

+0

을 참조하십시오.'alias'가 [alias_method'] (http://apidock.com/ruby/Module/alias_method)이 답변이 작성된 이후로? –

+0

@ JaredBeck 정말 이름이 바뀌 었습니다. 이제는 다음과 같아야합니다. alias_method : super_a : a –

29

좋은 방법은 없지만 작동 할 수는 있지만 추한 것입니다. A.instance_method(:a).bind(self).call.

당신은 자바에서 슈퍼처럼 행동하는 객체에 자신 만의 방법을 정의 할 수 있습니다 : 당신이 명시 적으로 오히려 B 번호의 B에서 A # A를 부르지 만, 할 필요가없는 경우

class SuperProxy 
    def initialize(obj) 
    @obj = obj 
    end 

    def method_missing(meth, *args, &blk) 
    @obj.class.superclass.instance_method(meth).bind(@obj).call(*args, &blk) 
    end 
end 

class Object 
    private 
    def sup 
    SuperProxy.new(self) 
    end 
end 

class A 
    def a 
    puts "In A#a" 
    end 
end 

class B<A 
    def a 
    end 

    def b 
    sup.a 
    end 
end 
B.new.b # Prints in A#a 
+8

@klochner,이 솔루션은 내가 ... 필요한 이유가 정확히 무엇을했다 : 나는 다른 방법의 일반적으로 호출 슈퍼 방법 싶었지만, 별명에 필요없이 내가 원하는 모든 하나 하나가 할 수 이를 위해 super를 호출하는 일반적인 방법은 매우 유용합니다. –

+3

한 번 정의하기가 복잡하여 여러 번 호출하기가 쉽습니다. 그 반대도 마찬가지입니다. – nertzy

0

필요 B # a에서 A # a를 호출하는 것입니다. B # b를 통해 실제로하는 일입니다. (예제가 B # b에서 전화하는 이유를 설명하기에 충분하지 않은 경우가 아니면 B # 내에서 super를 호출하십시오. 초기화 메소드에서 가끔씩 수행되는 것과 같습니다. 분명히 알 수 있습니다. 별칭을 사용하지 않아도되는 루비 신규 사용자를 명확히하고 싶습니다. "주위 별명") 모든 캐스 이자형. 나는 동의하지

class A 
    def a 
    # do stuff for A 
    end 
end 

class B < A 
    def a 
    # do some stuff specific to B 
    super 
    # or use super() if you don't want super to pass on any args that method a might have had 
    # super/super() can also be called first 
    # it should be noted that some design patterns call for avoiding this construct 
    # as it creates a tight coupling between the classes. If you control both 
    # classes, it's not as big a deal, but if the superclass is outside your control 
    # it could change, w/o you knowing. This is pretty much composition vs inheritance 
    end 
end 
관련 문제