我试图像这样扩展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
Run Code Online (Sandbox Code Playgroud)
Phr*_*ogz 11
class String
def clear!
replace ""
end
end
x = "foo"
x.clear!
p x
#=> ""
Run Code Online (Sandbox Code Playgroud)
同样可用: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 ""
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4543 次 |
| 最近记录: |