Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

235
Views
How can I replace words in a string with elements in an array in ruby?

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.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!