我正在尝试像这样扩展ruby字符串类:
String.class_eval do
def clear!
# Here I want the string value to be set to empty string. The following code is not working.
self = ''
end
end
答案 0 :(得分:11)
class String
def clear!
replace ""
end
end
x = "foo"
x.clear!
p x
#=> ""
同样可用:Array#replace
和Hash#replace
。
或者,不那么干净:
class String
def clear!
gsub! /.+/m, ''
end
end
class String
def clear!
slice!(0,-1)
end
end
# ...and so on; use any mutating method to set the contents to ""
答案 1 :(得分:3)
你可以这样做:
String.class_eval do
def clear!
self[0..-1] = ""
end
end
答案 2 :(得分:1)
看起来反直觉,我认为你应该使用String.instance_eval,因为你想要的是一个类方法: http://ilikestuffblog.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/
答案 3 :(得分:1)