Home > database >  How to replace / delete some of the special characters present in a string?
How to replace / delete some of the special characters present in a string?

Time:01-05

Context -

I have few strings which have some special characters in them which are supposed to be replaced / deleted to get the desired output.

What we need to do? -

Like I mentioned above -

  1. Delete the character '@' if any are present in the string.

  2. Replace the character '/' with '_'

For Instance -

Example 1) -

Input String -

string = noMad@/places/-/contents/imr/-/pops/-

Desired result-

output_string = noMad_places_-_contents_imr_-pops_-

Example 2) -

Input String -

string = cat@/places/-/chart/rules

Desired result-

output_string = cat_places_-_chart_rules

How can we do this in Ruby? Any leads would be appreciated!

CodePudding user response:

You can use a String class method named gsub() The basic syntax of gsub in Ruby:

str.gsub!(pattern, replacement)

Parameters: Here, str is the given string. pattern may be specified regex or character set to be removed. replacement is the set of characters which is to be put.

For example

string1 = "noMad@/places/-/contents/imr/-/pops/-"
puts string1.gsub("@","").gsub("/","_")

Output

noMad_places_-_contents_imr_-_pops_-

CodePudding user response:

Use tr

string = 'cat@/places/-/chart/rules'

p string.delete('@').tr('/','_')

output

"cat_places_-_chart_rules"
  • Related