Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass array to sub or gsub in ruby?

Tags:

ruby

I have an array of characters I want to be removed from a string:

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

I want to be able to pass the array and have all occurrences of those chars removed so that:

"str [with] unwanted# char*acters"

becomes

"str with unwanted characters"

like image 309
user1049097 Avatar asked Dec 02 '22 01:12

user1049097


2 Answers

"str [with] unwanted# char*acters".gsub(Regexp.union(stops), '')
# => "str with unwanted characters"
like image 89
sawa Avatar answered Jan 06 '23 07:01

sawa


If you need to remove characters you can use #delete

str.delete "[]^()#*?~"
like image 31
Yossi Avatar answered Jan 06 '23 07:01

Yossi