Is there a Regex Delete in Ruby?

One way is to add your own short methods:

class String

  def del(regexp)
    gsub(regexp,'')
  end

  def del!(regexp)
    gsub!(regexp,'')
  end

end

Typically this code would go in a lib/ directory, for example lib/string-extensions.rb

Heads up that some programmers really dislike this because it's monkey-patching. I personally like it for projects because it makes code easier to understand - once I have the "del" method, I can quickly see that calls to it are just deleting the regexp.


You could instead specify the part of the string you want to keep . . .

string[/[^\/]*$/]