nebulus nebulus - 1 month ago 13
Ruby Question

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)"

Answer

I suggest using the form of String#gsub that employs a hash for making substitutions.

strings_to_highlight = ['red', 'blue']

First construct the hash.

h = strings_to_highlight.each_with_object({}) do |s,h|
  h[s] = "(#{s})"
  ss = "#{s[0].swapcase}#{s[1..-1]}"
  h[ss] = "(#{ss})"
end
  #=> {"red"=>"(red)", "Red"=>"(Red)", "Blue"=>"(Blue)", "blue"=>"(blue)"} 

Next define a default proc for it:

h.default_proc = ->(h,k) { k }

so that if h does not have a key k, h[k] returns k (e.g., h["cat"] #=> "cat").

Ready to go!

string = "Roses are Red, violets are blue"

string.gsub(/[[[:alpha:]]]+/, h)
 => "Roses are (Red), violets are (blue)"

This should be relatively efficient as only one pass through the string is needed and hash lookups are very fast.

Comments