Ruby on rails 如何在Ruby中调用super.super方法
我有以下课程Ruby on rails 如何在Ruby中调用super.super方法,ruby-on-rails,ruby,Ruby On Rails,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 类动物 d
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
类动物
def移动
“我可以走了”
结束
结束
鸟类<动物
def移动
超级+“通过飞行”
结束
结束
企鹅类
def移动
#我怎么能叫动物搬家
“我可以移动”+“游泳”
结束
结束
企鹅体内的动物移动法怎么叫?我不能用super.super.move。有哪些选择
谢谢您可以获得
动物
的移动
实例方法,将其绑定到自我
,然后调用它:
class Penguin < Bird
def move
m = Animal.instance_method(:move).bind(self)
m.call
end
end
class企鹅
企鹅类
有关此方法的更多详细信息,请阅读您可以这样做(我建议):
class企鹅
[编辑:我发现这与@August的答案非常相似。这有一点好处,即类
动物和方法名移动都不是硬连接的。]如果您使用的是Ruby 2.2.0,那么您就有了新的东西。那东西是:
类动物
def移动
“我可以走了”
结束
结束
鸟类<动物
def移动
超级+“通过飞行”
结束
结束
企鹅类
def移动
method(uuu method)。super_method.super_method.call+“通过游泳”
结束
结束
Penguin.new.move#=>“我可以通过游泳来移动”
我完全同意他的观点,他的答案是最好的和干净的。如果你喜欢设计,公认的解决方案不是最好的选择。最好的答案是-,这很酷。如果方便,您也可以这样做:class方法;def-u法(n);n、 减少(自我){m,{m.super_方法};结束;结束,然后方法(\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu方法)。调用+“通过游泳”
。
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
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
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"