如何在Ruby中调用super.super方法

Toa*_*yen 3 ruby ruby-on-rails

我有以下课程

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
Run Code Online (Sandbox Code Playgroud)

如何在Penguin中调用Animal的移动方法?我不能使用super.super.move.有什么选择?

谢谢

Aug*_*ust 8

你可以获取move实例方法Animal,绑定它self,然后调用它:

class Penguin < Bird
  def move
    m = Animal.instance_method(:move).bind(self)
    m.call
  end
end
Run Code Online (Sandbox Code Playgroud)


Aru*_*hit 6

如果您使用的是 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"
Run Code Online (Sandbox Code Playgroud)

我完全同意Robert Klemme's,他的回答是最好的、干净的。