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?
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
Ruby | Set delete() function The delete() is an inbuilt method in Ruby which deletes the given object from the set and returns the self object. In case the object is not present, it returns self only. Parameters: The function takes a mandatory parameter object which is to be deleted.
chop is a String class method in Ruby which is used to return a new String with the last character removed. Both characters are removed if the string ends with \r\n, b. Applying chop to an empty string returns an empty string.
Removing the first character To remove the first character of a string in Ruby, we can use the built-in slice!() method by passing a character index.
Do as below using String#tr
:
"((String1))".tr('()', '') # => "String1"
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With