1

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.

0

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

More simply gsub can take a hash as a second argument structured as a {match => replacement} e.g. s.gsub(/\{\{(?:width|length)\}\}/,h) #=> "The dimension of the square is 10 and 20"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.