Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to reference ruby regular expressions

Tags:

regex

ruby

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>")
like image 700
boostbob Avatar asked Dec 27 '22 04:12

boostbob


2 Answers

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>")
like image 152
Shawn Balestracci Avatar answered Feb 11 '23 09:02

Shawn Balestracci


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.

like image 39
Zifei Tong Avatar answered Feb 11 '23 09:02

Zifei Tong