开发者

Extend Ruby String class with method to change the contents

I am trying to extend the ruby stri开发者_如何学Gong class like this:

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


Use String#replace:

class String
  def clear!
    replace ""
  end
end

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

Similarly available: Array#replace and Hash#replace.

Alternatively, and far less cleanly:

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 ""


You could do this:

String.class_eval do
  def clear!
    self[0..-1] = ""
  end
end


As counter-intuitive as it seems, I think you should be using String.instance_eval because what you want is a class method: http://ilikestuffblog.com/2009/01/09/fun-with-rubys-instance_eval-and-class_eval/


Easy:

class String
  alias_method :clear!, :clear
end

Although I'm not sure what your String#clear! provides over the existing String#clear method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜