开发者

Ruby - Overriding string methods in a separate file

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 required 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'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜