加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-17 01:42:47 所属栏目:百科 来源:网络整理
导读:我有以下课程 class Animal def move "I can move" endendclass Bird Animal def move super + " by flying" endendclass Penguin Bird def move #How can I call Animal move here "I can move"+ ' by swimming' endend 如何在Penguin中调用Animal的移动方
我有以下课程

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.有什么选择?

谢谢

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读