我希望我的模块的一部分扩展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!!!!!"
@R_403_323@
第一个示例中的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