How to pass an array to sub or gsub in ruby?

I have an array of characters that I want to remove from a string:

stops = ["[", "]", "^", "(", ")", "#", "*", "?", "~"]

I want to be able to pass an array and remove all occurrences of these characters so that:

"str [with] unwanted# char*acters"

becomes

"str with unwanted characters"

+4
source share
3 answers

If you need to delete characters, you can use #delete

 str.delete "[]^()#*?~" 
+9
source
 "str [with] unwanted# char*acters".gsub(Regexp.union(stops), '') # => "str with unwanted characters" 
+10
source
 str.tr('[]^()#*?~','') str.tr('[]^()#*?~','abcdefghi') 
0
source

Source: https://habr.com/ru/post/1381453/


All Articles