2009-08-09 10 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を実行することができますが、醜いです。

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、この解決策は、私が必要な正確に何...その理由だった:私は別の方法の総称的に呼び出し、スーパー方法を望んでいたが、私はできるようにしたかったひとつひとつの1を別名することなく、これを行うためには、superを呼び出す一般的な方法は非常に便利です –

+3

一度定​​義するのは複雑で、多くの時間を簡単に呼び出すことは簡単です。それは逆です。 – nertzy

0

明示的にBの#bからの#aを呼び出す必要があるのではなく、必要がない場合:あなたもJavaでスーパーのように動作するオブジェクトで、独自のメソッドを定義することができ

B#aからA#aを呼び出すことができます。これは、B#bを使用して実際に行っていることです(例では、B#bから呼び出す理由を示すのに十分ではない場合を除き、 B#aからsuperを呼び出す、ちょうど時には初期化メソッドで行われるのと同じように。私はこれが一種のものであることを知っている、私はちょうどエイリアスする必要がないRuby new-comersを明確にしたかった。 「周りのエイリアス」) e。私は同意

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 
関連する問題