Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a Regex Delete in Ruby?

All of my string delete's with regex use gsub, is there a shorter way? string.gsub(/\A.*\//,'')

like image 947
Mr. Demetrius Michael Avatar asked Mar 31 '12 21:03

Mr. Demetrius Michael


2 Answers

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.

like image 66
joelparkerhenderson Avatar answered Oct 17 '22 02:10

joelparkerhenderson


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

string[/[^\/]*$/]
like image 39
DigitalRoss Avatar answered Oct 17 '22 03:10

DigitalRoss