我已经在String类中替换了一个方法to_s,但正如我所看到的,当我运行时puts "string",ruby调用的不是to_s方法.
def add_method(cls)
cls.class_eval do
def initialize
self.new('you hacked')
end
def to_s
'you hacked'
end
end
end
add_method String
puts "zxzxzzx"
puts "zxzxzzx".to_s
Run Code Online (Sandbox Code Playgroud)
哪个输出:
>> zxzxzzx
>> you hacked
Run Code Online (Sandbox Code Playgroud)
如何替换这种隐式初始化?