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[/[^\/]*$/]
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.
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 :)
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 :)
[[:word:]]
. Is it possible? ruby-doc.org/core-3.1.1/… –
Pentathlon © 2022 - 2024 — McMap. All rights reserved.
delete
doesn't take a regex. You can always create a String method likegdel
or something that does what you want. – Quintongsub
(instead ofsub
) 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. – Floodgate