How to delete specific characters from a string in Ruby?

RubyStringTrim

Ruby Problem Overview


I have several strings that look like this:

"((String1))"

They are all different lengths. How could I remove the parentheses from all these strings in a loop?

Ruby Solutions


Solution 1 - Ruby

Do as below using String#tr :

 "((String1))".tr('()', '')
 # => "String1"

Solution 2 - Ruby

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 - Ruby

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 - Ruby

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 - Ruby

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"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionCristianoView Question on Stackoverflow
Solution 1 - RubyArup RakshitView Answer on Stackoverflow
Solution 2 - RubyjbrView Answer on Stackoverflow
Solution 3 - Rubydaino3View Answer on Stackoverflow
Solution 4 - RubyfalsetruView Answer on Stackoverflow
Solution 5 - Rubyz atefView Answer on Stackoverflow