0
我有一个'example.rb'文件,我想通过重写字符串类在String上使用自定义方法。Ruby - 在单独文件中重写字符串方法
我知道这是可以做到
puts "abcd".twice
class String
def twice
self*2
end
end
但我想有自定义的方法定义在另一个文件中,说“my_String.rb”。我该怎么做呢?
我有一个'example.rb'文件,我想通过重写字符串类在String上使用自定义方法。Ruby - 在单独文件中重写字符串方法
我知道这是可以做到
puts "abcd".twice
class String
def twice
self*2
end
end
但我想有自定义的方法定义在另一个文件中,说“my_String.rb”。我该怎么做呢?
做你的猴子修补在“my_string.rb”(或其他),并有文件require
d在你的脚本中。
# 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
您只需将字符串班开班方法my_string.rb并在代码中你做:
require 'my_string'
干杯人,像冠军一样工作 – theReverseFlick 2011-02-13 07:21:11