How to replace words from an array in a string with asterisks?

Viewed 54

I have a string, that contains a sentence. Then I have an array, that have some words. I need to check, if that sentence contains words given in the array, or more specifically, even if words from the array are parts of the words in that sentence. Case insensitive. In case there are matches, I need to change the words in that sentence to something else, for ex. "*****". I have tried different options like: any?, include?, gsub, but didn't manage to make it work properly. Would be very grateful for any help!

For example:

array = ['ga', 'day', 'sky']
string = "Peter went to the garden, to gather oranges. It was a sunny day and there were a lot of birds in the sky."

array.each do |word|
  if string.include? (word)
    temp.gsub(word, "*****") # or temp[word] = "*****"
  end
end

Desired output for printing the string would be:

Peter went to the *****, to ***** oranges. It was a sunny ***** and there were a lot of birds in the *****.

1 Answers

"if string.include? (word)" is excess here, as you will iterate through string 1 unnecessary time. May be you just forgot to declare temp. This should work

temp = string
array.each do |word|
   temp = temp.gsub(word, "*****") 
end

If you want to have same ammount of "*" as in word. Change "****", to "*"*word.length

If you want to change original string. Just use string = string.gsub(word, "*") gsub is not changing original string, but creates new one. You have to store it.

Related