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

ruby – 基本元编程:使用模块扩展现有类?

发布时间:2020-12-17 04:38:49 所属栏目:百科 来源:网络整理
导读:我希望我的模块的一部分扩展String类. 这不起作用 module MyModule class String def exclaim self "!!!!!" end endendinclude MyModulestring = "this is a string"string.exclaim#= NoMethodError 但这样做 module MyModule def exclaim self "!!!!!" ende
我希望我的模块的一部分扩展String类.

这不起作用

module MyModule
  class String
    def exclaim
      self << "!!!!!"
    end
  end
end

include MyModule

string = "this is a string"
string.exclaim

#=> NoMethodError

但这样做

module MyModule
  def exclaim
    self << "!!!!!"
  end
end

class String
  include MyModule
end

string = "this is a string"
string.exclaim

#=> "this is a string!!!!!"

我不希望MyModule的所有其他功能都在String中.在最高级别再次包括它似乎很难看.当然有一种更简洁的方法吗?

解决方法

第一个示例中的exclaim方法是在名为MyModule :: String的类中定义的,该类与标准String类无关.

在您的模块中,您可以打开标准的String类(在全局命名空间中),如下所示:

module MyModule
  class ::String
    # ‘Multiple exclamation marks,’ he went on,shaking his head,# ‘are a sure sign of a diseased mind.’ — Terry Pratchett,“Eric”
    def exclaim
      self << "!!!!"
    end
  end
end

(编辑:李大同)

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

    推荐文章
      热点阅读