私はモジュールの一部でStringクラスを拡張したいと思います。基本メタプログラミング:モジュールを使用して既存のクラスを拡張するか?
これは
module MyModule
class String
def exclaim
self << "!!!!!"
end
end
end
include MyModule
string = "this is a string"
string.exclaim
#=> NoMethodError
を動作しません。しかし、これは私がMyModuleというの他のすべての機能を文字列に置き去りにされたくない
module MyModule
def exclaim
self << "!!!!!"
end
end
class String
include MyModule
end
string = "this is a string"
string.exclaim
#=> "this is a string!!!!!"
を行います。最高レベルで再びそれを含むことは醜いようです。確かにこれを行うためのより純粋な方法がありますか?
非常に便利です。ありがとうございました。 – djb
コメントの引用のためにUpvoted :-) – vijucat