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

前端之家收集整理的这篇文章主要介绍了ruby – 基本元编程:使用模块扩展现有类?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我希望我的模块的一部分扩展String类.

这不起作用

  1. module MyModule
  2. class String
  3. def exclaim
  4. self << "!!!!!"
  5. end
  6. end
  7. end
  8.  
  9. include MyModule
  10.  
  11. string = "this is a string"
  12. string.exclaim
  13.  
  14. #=> NoMethodError

但这样做

  1. module MyModule
  2. def exclaim
  3. self << "!!!!!"
  4. end
  5. end
  6.  
  7. class String
  8. include MyModule
  9. end
  10.  
  11. string = "this is a string"
  12. string.exclaim
  13.  
  14. #=> "this is a string!!!!!"

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

@R_403_323@

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

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

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

猜你在找的Ruby相关文章