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

时间:2011-07-22 16:59:20

标签: 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

4 个答案:

答案 0 :(得分:11)

使用String#replace

class String
  def clear!
    replace ""
  end
end

x = "foo"
x.clear!
p x
#=> ""

同样可用: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 ""

答案 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)

易:

class String
  alias_method :clear!, :clear
end

虽然我不确定String#clear!对现有String#clear方法提供的内容。