[英]How to call super.super method in Ruby
I have the following classes 我有以下课程
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
How can I call Animal's move method inside Penguin ? 如何在Penguin中调用Animal的移动方法? I can't use super.super.move. 我不能使用super.super.move。 What are the options? 有什么选择?
Thanks 谢谢
You can get the move
instance method of Animal
, bind it to self
, then call it: 你可以获得Animal
的move
实例方法,将它绑定到self
,然后调用它:
class Penguin < Bird
def move
m = Animal.instance_method(:move).bind(self)
m.call
end
end
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
For more details about this approach read this answer 有关此方法的更多详细信息,请阅读此答案
You could do this (which I suggested 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
[Edit: I see this is quite similar to @August's answer. [编辑:我认为这与@ August的回答非常相似。 This has the slight advantage that neither the class Animal
nor method name move
are hard-wired.] 这有微弱的优势,无论是类Animal
,也没有方法名move
硬连线]
If you are using Ruby 2.2.0, then you have something new in your plate. 如果你使用的是Ruby 2.2.0,那么你的盘子里就有了新东西。 That something is : Method#super_method
. 这事情是: 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"
I completely agree with Robert Klemme's
and his answer is best and clean. 我完全同意Robert Klemme's
说法,他的回答是最好的和干净的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.