2011-04-23 114 views
1

我想在Ruby中定義一些具有繼承層次結構的類,但是我想使用派生類中基類中的某個方法。問題的關鍵在於我不想調用我正在使用的確切方法,我想調用一個不同的方法。以下不起作用,但這是我想要做的(基本上)。在Ruby中調用超級方法

class A 
    def foo 
     puts 'A::foo' 
    end 
end 

class B < A 
    def foo 
     puts 'B::foo' 
    end 
    def bar 
     super.foo 
    end 
end 

回答

5

可能這就是你想要的嗎?

class A 
    def foo 
    puts 'A::foo' 
    end 
end 

class B < A 
    alias bar :foo 
    def foo 
    puts 'B::foo' 
    end 
end 

B.new.foo # => B::foo 
B.new.bar # => A::foo 
+0

哦,嘿。這真的很方便。所以它的別名是#{new}:#{old}'? – 2011-04-23 06:28:07

+1

對。關鍵的是,「別名」是即時評估的。所以,如果你在'B#foo'的定義之後加上'alias',它將不起作用。它會變成'B#foo'。 – sawa 2011-04-23 06:29:43

0

更通用的解決方案。

class A 
    def foo 
    puts "A::foo" 
    end 
end 

class B < A 
    def foo 
    puts "B::foo" 
    end 
    def bar 
    # slightly oddly ancestors includes the class itself 
    puts self.class.ancestors[1].instance_method(:foo).bind(self).call 
    end 
end 

B.new.foo # => B::foo 
B.new.bar # => A::foo