2015-01-21 78 views
2

我有以下類如何調用super.super方法在Ruby中

class Animal 
    def move 
    "I can move" 
    end 
end 

class Bird < Animal 
    def move 
    super + " by flying" 
    end 
end 

class Penguin < Bird 
    def move 
    #How can I call Animal move here 
    "I can move"+ ' by swimming' 
    end 
end 

我怎麼能說裏面企鵝動物的舉動方法?我不能使用super.super.move。有什麼選擇?

感謝

+1

如果您喜歡_designs_,接受的解決方案並不是最好的選擇。最佳答案是 - [我們如何在Ruby中調用父母的父方法?](http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/429729)。 – 2015-01-21 10:17:18

+1

@Arup,我同意。 – 2015-01-26 05:16:31

回答

7

你可以得到的Animalmove實例方法,將其綁定到self,然後調用它:

class Penguin < Bird 
    def move 
    m = Animal.instance_method(:move).bind(self) 
    m.call 
    end 
end 
1
class Penguin < Bird 
    def move 
    grandparent = self.class.superclass.superclass 
    meth = grandparent.instance_method(:move) 
    meth.bind(self).call + " by swimming" 
    end 
end 

puts Penguin.new.move 

有關此方法的詳細信息,閱讀this answer

1

你可以這樣做(我建議here):

class Penguin < Bird 
    def move 
    puts self.class.ancestors[2].instance_method(__method__).bind(self).call + 
    ' by swimming' 
    end 
end 

Penguin.new.move 
    # I can move by swimming 

[編輯:我看到這與@ August的答案很相似。這具有輕微的優勢,即Animalmove都不是硬連線。]

1

如果您使用的是Ruby 2.2.0,那麼您的盤中就有新的東西。那東西是:Method#super_method

class Animal 
    def move 
    "I can move" 
    end 
end 

class Bird < Animal 
    def move 
    super + " by flying" 
    end 
end 

class Penguin < Bird 
    def move 
    method(__method__).super_method.super_method.call + ' by swimming' 
    end 
end 

Penguin.new.move # => "I can move by swimming" 

我完全同意Robert Klemme's和他的答案是最好的,乾淨。

+0

這很酷。如果方便的話,你也可以這樣做:'class Method; def ancestor_method(n); n×reduce(self){| m,_ | m.super_method};結束; end',然後'method(__ method __)。ancestor_method(2).call +'by swimming''。 – 2015-02-06 02:29:09

相關問題