ruby-on-rails - 如何在 Ruby 中调用 super.super 方法

标签 ruby-on-rails ruby

我有以下类(class)

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

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

谢谢

最佳答案

可以获取Animalmove实例方法,绑定(bind)到self,然后调用:

class Penguin < Bird
  def move
    m = Animal.instance_method(:move).bind(self)
    m.call
  end
end

关于ruby-on-rails - 如何在 Ruby 中调用 super.super 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28058336/

相关文章:

ruby-on-rails - Capistrano 部署问题

ruby-on-rails - 从患有特定疾病的用户那里查找疾病

ruby - 将运算符传递给函数?

ruby - 使用redis存储结构化事件日志

ruby-on-rails - Assets 管道损坏 : Not compiling on the fly css and js files

ruby-on-rails - 当页面有几个相同的链接时, capybara 的 "click_link"方法如何知道点击哪个链接?

ruby-on-rails - 使用 Liquid 作为 Ruby on Rails 布局

ruby-on-rails - Rails link_to params .id 而不是/id

ruby-on-rails - 如何在具有不同表名的 Rails 迁移中添加外键

ruby-on-rails - Rails 生成命令不起作用