All of my string delete's with regex use gsub, is there a shorter way?
string.gsub(/\A.*\//,'')
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[/[^\/]*$/]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With