I have a file, 'example.rb', where I want to use custom methods on String by overriding the string class.
I know this can be done as
put开发者_高级运维s "abcd".twice
class String
def twice
self*2
end
end
But I want to have the custom methods definition in another file, say 'my_String.rb'. How do I do this?
Do your monkey patching in "my_string.rb" (or whatever) and have the file require
d in your script.
# my_string.rb
class String
def twice
self*2
end
end
# my_super_script.rb
require 'my_string.rb' # Assuming both these files are in the same folder
puts "abcd".twice
You simply put the String class opening method in my_string.rb and in your code you do:
require 'my_string'
精彩评论