使用方法扩展Ruby String类以更改内容

Aru*_*nan 3 ruby

我试图像这样扩展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

用途String#replace:

class String
  def clear!
    replace ""
  end
end

x = "foo"
x.clear!
p x
#=> ""
Run Code Online (Sandbox Code Playgroud)

同样可用:Array#replaceHash#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)