Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace words in a string based on words in an Array in Ruby?

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)"
like image 303
masterial Avatar asked Jan 17 '26 15:01

masterial


2 Answers

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)
like image 125
spike Avatar answered Jan 20 '26 15:01

spike


strings_to_highlight = ['red', 'blue']
string = "Roses are red, violets are blue"

strings_to_highlight.each { |i| string.gsub!(/\b#{i}\b/, "(#{i})")}
like image 29
C dot StrifeVII Avatar answered Jan 20 '26 13:01

C dot StrifeVII



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!