【发布时间】:2011-08-30 11:22:07
【问题描述】:
我希望我的模块的一部分可以扩展 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 中被隔离。在最高级别再次包括它似乎很难看。肯定有更简洁的方法吗?
【问题讨论】:
标签: ruby scope metaprogramming