基本元编程:使用模块扩展现有类?
我希望我的模块的一部分扩展 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 中。再次将其纳入最高级别似乎很丑陋。当然有一种更简洁的方法可以做到这一点吗?
I'd like part of my module to extend the String class.
This doesn't work
module MyModule
class String
def exclaim
self << "!!!!!"
end
end
end
include MyModule
string = "this is a string"
string.exclaim
#=> NoMethodError
But this does
module MyModule
def exclaim
self << "!!!!!"
end
end
class String
include MyModule
end
string = "this is a string"
string.exclaim
#=> "this is a string!!!!!"
I don't want all the other functionality of MyModule to be marooned in String. Including it again at the highest level seems ugly. Surely there is a neater way of doing this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
第一个示例中的
exclaim
方法是在名为MyModule::String
的类中定义的,该类与标准String
类无关。在模块内部,您可以打开标准
String
类(在全局命名空间中),如下所示:The
exclaim
method in your first example is being defined inside a class calledMyModule::String
, which has nothing to do with the standardString
class.Inside your module, you can open the standard
String
class (in the global namespace) like this:我不确定我是否理解了你的问题,但为什么不在文件中打开字符串,例如 exclaim.rb,然后在需要时需要它:
exclaim.rb
然后
但也许我错过了一些东西?
I'm not sure I've understood your question but why don't open string in a file, say exclaim.rb, and then require it when you need it:
exclaim.rb
and then
But maybe I'm missing something?