djb*_*djb 8 ruby scope metaprogramming
我希望我的模块的一部分扩展String类.
这不起作用
module MyModule
class String
def exclaim
self << "!!!!!"
end
end
end
include MyModule
string = "this is a string"
string.exclaim
#=> NoMethodError
Run Code Online (Sandbox Code Playgroud)
但这样做
module MyModule
def exclaim
self << "!!!!!"
end
end
class String
include MyModule
end
string = "this is a string"
string.exclaim
#=> "this is a string!!!!!"
Run Code Online (Sandbox Code Playgroud)
我不希望MyModule的所有其他功能都被串在String中.在最高级别再次包括它似乎很难看.当然有一种更简洁的方法吗?
Lar*_*eth 26
第exclaim一个示例中的方法是在一个名为class的类中定义的,该类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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4267 次 |
| 最近记录: |