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

- 2,326
- 5
- 28
- 40
-
3Those three characters really getting to you? – Dave Newton Mar 31 '12 at 21:50
-
lol seem to be doing a lot of string deletes. But doing it via gsub, seems like I'm doing it wrong. It should be done via string.delete, no? – Mr. Demetrius Michael Mar 31 '12 at 21:54
-
string.delete only takes what characters to delete, no regexp. string.slice! can be used to remove part of a string based on a regexp but is's longer then gsub... – Pafjo Mar 31 '12 at 22:02
-
`delete` doesn't take a regex. You can always create a String method like `gdel` or something that does what you want. – Dave Newton Mar 31 '12 at 22:03
-
Do you need to do that in one position per string or multiple positions? Your expression has `gsub` (instead of `sub`) which means you are expecting multiple matches, but you also have `\A` in the regex, which means you are expecting only one match. Depending on that, solutions become different. – sawa Mar 31 '12 at 23:21
-
Multiple positions, sorry copied one of the gsubs as a poor example. I'm just surprised delete doesn't incorporate regex. Seems like it'll be more consistent with Ruby's ideology if it did. – Mr. Demetrius Michael Apr 02 '12 at 21:18
4 Answers
You could instead specify the part of the string you want to keep . . .
string[/[^\/]*$/]

- 143,651
- 25
- 248
- 329
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.

- 34,808
- 19
- 98
- 119
I don't think so.
String::delete deletes characters, and does not match regex, it's a completely different approach.
The only way I can think of making that line of yours "shorter" is to use string.gsub!(/\A.*\//,'')
(notice the bang there).
That's the way to go, I think :)

- 3,147
- 16
- 15
You can use String::delete by specifying a regex in the argument.
Say you want to delete all non AlphaNumeric from a string...
a="Test String with &(*ille#*)gal char!@#acters ^lorem % ipsum $"
a.delete!('^a-zA-Z0-9 .')
Ofcourse be careful to include Whitespace and DOT
Above code will yield the following output
"Test String with illegal characters lorem ipsum "
This is just an example.
Hope this helps :)

- 21
- 2
-
I haven't been able to use delete with POSIX bracket expressions like `[[:word:]]`. Is it possible? https://ruby-doc.org/core-3.1.1/Regexp.html#class-Regexp-label-Character+Classes – chemturion Mar 11 '22 at 16:08