JBWyatt4 JBWyatt4 - 4 months ago 8
Ruby Question

Replace a keyword+value with a string infront and behind the value

Using Ruby, in a string I want to replace

something...
specialstring=360256
something...


with

something...
<script src="https://gist.github.com/someuser/360256.js"></script>
something...


I believe it can be done with a Regex (maybe gsub), but I am afraid I am just not that proficient.

Edit: "something... " indicates text that should not be changed. I want to replace all instances of

specialstring=10000


with the below in the string (extract the number)

<script src="https://gist.github.com/someuser/10000.js"></script>


Where 10000 can be any number terminated by a newline.

Answer
▶ input = %|something...
▷ specialstring=360256
▷ something...|
#⇒ "something...\nspecialstring=360256\nsomething..."
▶ out_tmpl = '<script src="https://gist.github.com/someuser/%{tmpl}.js"></script>'
▶ puts input.gsub(/^specialstring=(.*)$/) { out_tmpl % { tmpl: $1.strip }}
#⇒ something...
#  <script src=\"https://gist.github.com/someuser/360256.js\"></script>
#  something...

This is more-or-less generic solution, that parses input for occurrences of specialstring=ANYTHING, and then, using string formatting, injects this ANYTHING into the template, substituting the original pattern.