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

我希望我的模块的一部分扩展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

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...