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

扩展时的Ruby调用模块方法

发布时间:2020-12-17 02:24:19 所属栏目:百科 来源:网络整理
导读:给定一个基本的 ruby类和模块,有一种方法可以在扩展类的实例时立即从模块调用方法吗? class Dog def initialize(name) @name = name end endmodule Speech def say_name puts @name end # call to method in module ? say_nameendfido = Dog.new('fido')fid
给定一个基本的 ruby类和模块,有一种方法可以在扩展类的实例时立即从模块调用方法吗?

class Dog 
  def initialize(name)
    @name = name 
  end 
end

module Speech
  def say_name
    puts @name
  end
  # call to method in module ?
  say_name
end

fido = Dog.new('fido')
fido.extend Speech    => *'fido'*

我知道’included’方法在包含模块时有点像回调,但我希望有类似的东西用于扩展.

解决方法

这是使用方法 extend_object的一个技巧.

Extends the specified object by adding this module’s constants and methods (which are added as singleton methods). This is the callback method used by Object#extend.

class Dog 
  def initialize(name)
    @name = name 
  end 
end

module Speech
  def Speech.extend_object(o)
    super
    puts o.say_name
  end

  def say_name
    @name
  end
end

fido = Dog.new('fido')
fido.extend Speech # 'fido'

(编辑:李大同)

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

    推荐文章
      热点阅读