Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to delete specific characters from a string in Ruby?

Tags:

string

trim

ruby

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?

like image 264
Cristiano Avatar asked Oct 28 '13 14:10

Cristiano


People also ask

How do I remove a specific character from a string?

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.

How do I use Delete in Ruby?

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.

What does Chop do in Ruby?

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.

How do you remove the first character of a string in Ruby?

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.


2 Answers

Do as below using String#tr :

 "((String1))".tr('()', '')  # => "String1" 
like image 186
Arup Rakshit Avatar answered Sep 24 '22 13:09

Arup Rakshit


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" 
like image 31
jbr Avatar answered Sep 23 '22 13:09

jbr