How to delete specific characters from a string in Ruby?
Solution 1:
Do as below using String#tr
:
"((String1))".tr('()', '')
# => "String1"
Solution 2:
If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:
s = "((String1))"
s = s[2...-2]
p s # => "String1"
If you want to remove all parentheses from the string you can use the delete method on the string class:
s = "((String1))"
s.delete! '()'
p s # => "String1"
Solution 3:
For those coming across this and looking for performance, it looks like #delete
and #tr
are about the same in speed and 2-4x faster than gsub
.
text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04
Solution 4:
Using String#gsub
with regular expression:
"((String1))".gsub(/^\(+|\)+$/, '')
# => "String1"
"(((((( parentheses )))".gsub(/^\(+|\)+$/, '')
# => " parentheses "
This will remove surrounding parentheses only.
"(((((( This (is) string )))".gsub(/^\(+|\)+$/, '')
# => " This (is) string "
Solution 5:
Here is an even shorter way of achieving this:
1) using Negative character class pattern matching
irb(main)> "((String1))"[/[^()]+/]
=> "String1"
^
- Matches anything NOT in the character class. Inside the charachter class, we have (
and )
Or with global substitution "AKA: gsub" like others have mentioned.
irb(main)> "((String1))".gsub(/[)(]/, '')
=> "String1"