103

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?

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
Cristiano
  • 2,839
  • 8
  • 25
  • 35

6 Answers6

196

Do as below using String#tr :

 "((String1))".tr('()', '')
 # => "String1"
Nakilon
  • 34,866
  • 14
  • 107
  • 142
Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
49

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"
jbr
  • 6,198
  • 3
  • 30
  • 42
30

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
daino3
  • 4,386
  • 37
  • 48
  • 4
    Four years later... :-) I find if I up your benchmarking by a couple orders of magnitude (1_000_000 runs), that with the same code you use above, I do get delete running slightly faster than tr, with delete at about a 0.92 ratio of tr, and gsub a little less than 1.5x of delete (actually ~ 1.46 of delete, and ~ 1.39 of tr). ymmv of course. This is on Ruby 2.6.3 on a 2018 MBP 13. Thanks for benchmarking these three methods! – likethesky Aug 18 '19 at 22:00
22

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 "
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

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"
z atef
  • 7,138
  • 3
  • 55
  • 50
  • Your two answers have different results on `((a))b`. The first will only return `a`, the second will return `ab` – Ulysse BN Oct 01 '18 at 12:59
1

Use String#delete:

"((String1))".delete "()"
=> "String1"
Pavel Chuchuva
  • 22,633
  • 10
  • 99
  • 115