Home > Net >  How can I replace words in a string with elements in an array in ruby?
How can I replace words in a string with elements in an array in ruby?

Time:10-21

I'm trying to replace words (sequence of characters, more generally) in a string with corresponding values in an array. An example is:

"The dimension of the square is {{width}} and {{length}}" with array [10,20] should give

"The dimension of the square is 10 and 20"

I have tried to use gsub as

substituteValues.each do |sub|
    value.gsub(/\{\{(.*?)\}\}/, sub)
end

But I could not get it to work. I have also thought of using a hash instead of an array as follows:

{"{{width}}"=>10, "{{height}}"=>20}. I feel this might work better but again, I'm not sure how to code it (new to ruby). Any help is appreciated.

CodePudding user response:

You can use

h = {"{{width}}"=>10, "{{length}}"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(?:width|length)\}\}/, h)
# => The dimension of the square is 10 and 20

See the Ruby demo. Details:

  • \{\{(?:width|length)\}\} - a regex that matches
    • \{\{ - a {{ substring
    • (?:width|length) - a non-capturing group that matches width or length words
    • \}\} - a }} substring
  • gsub replaces all occurrences in the string with
  • h - used as the second argument, allows replacing the found matches that are equal to hash keys with the corresponding hash values.

You may use a bit simpler hash definition without { and } and then use a capturing group in the regex to match length or width. Then you need

h = {"width"=>10, "length"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(width|length)\}\}/) { h[Regexp.last_match[1]] }

See this Ruby demo. So, here, (width|length) is used instead of (?:width|length) and only Group 1 is used as the key in h[Regexp.last_match[1]] inside the block.

  • Related