how would I do the following? I tried doing this gsub but I can't figure out what really efficient if strings_to_highlight array is large. Cheers!
string = "Roses are red, violets are blue"
strings_to_highlight = ['red', 'blue']
# ALGORITHM HERE
resulting_string = "Roses are (red), violets are (blue)"
Regexp has a helpful union function for combining regular expressions together. Stick with regexp until you have a performance problem:
string = "Roses are red, violets are blue"
strings_to_highlight = ['red', 'blue']
def highlight(str, words)
matcher = Regexp.union words.map { |w| /\b(#{Regexp.escape(w)})\b/ }
str.gsub(matcher) { |word| "(#{word})" }
end
puts highlight(string, strings_to_highlight)
strings_to_highlight = ['red', 'blue']
string = "Roses are red, violets are blue"
strings_to_highlight.each { |i| string.gsub!(/\b#{i}\b/, "(#{i})")}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With