I want to convert the string:
"{john:123456}"
to:
"<script src='https://gist.github.com/john/123456.js'>"
I wrote a method that works, but it is very stupid. It is like this:
def convert
args = []
self.scan(/{([a-zA-Z0-9\-_]+):(\d+)}/) {|x| args << x}
args.each do |pair|
name = pair[0]
id = pair[1]
self.gsub!("{" + name + ":" + id + "}", "<script src='https://gist.github.com/#{name}/#{id}.js'></script>")
end
self
end
Is there a way to do this just like the cool_method
below?
"{john:123}".cool_method(/{([a-zA-Z0-9\-_]+):(\d+)}/, "<script src='https://gist.github.com/$1/$2.js'></script>")
That cool method is gsub. You were so close! Just change the $1 and $2 to \\1 and \\2
http://ruby-doc.org/core-2.0/String.html#method-i-gsub
"{john:123}".gsub(/{([a-zA-Z0-9\-_]+):(\d+)}/,
"<script src='https://gist.github.com/\\1/\\2.js'></script>")
I would do
def convert
/{(?<name>[a-zA-Z0-9\-_]+):(?<id>\d+)}/ =~ self
"<script src='https://gist.github.com/#{name}/#{id}.js'></script>"
end
Please see http://ruby-doc.org/core-2.0/Regexp.html#label-Capturing for more details.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With