<\/script>')

How to reference Ruby regular expressions

I want to convert a string:

"{john:123456}" 

in

 "<script src='https://gist.github.com/john/123456.js'>" 

I wrote a method that works, but it is very stupid. This is something 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 cool_method below?

 "{john:123}".cool_method(/{([a-zA-Z0-9\-_]+):(\d+)}/, "<script src='https://gist.github.com/$1/$2.js'></script>") 
+4
source share
4 answers

This cool method is gsub. You were so close! Just change $ 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>") 
+7
source

I would do

 def convert /{(?<name>[a-zA-Z0-9\-_]+):(?<id>\d+)}/ =~ self "<script src='https://gist.github.com/#{name}/#{id}.js'></script>" end 

See http://ruby-doc.org/core-2.0/Regexp.html#label-Capturing for more details.

+1
source
 s = "{john:123456}".scan(/\w+|\d+/).each_with_object("<script src='https://gist.github.com") do |i,ob| ob<< "/" + i end.concat(".js'>") ps #=> "<script src='https://gist.github.com/john/123456.js'>" 
+1
source

This looks like a JSON string, so, as @DaveNewton said, treat it as one:

 require 'json' json = '{"john":123456}' name, value = JSON[json].flatten "<script src='https://gist.github.com/#{ name }/#{ value }.js'></script>" => "<script src='https://gist.github.com/john/123456.js'></script>" 

Why not consider it as a string and use regex on it? Since JSON is not a simple format for parsing with regular expressions, which can lead to errors when changing values, or the data string becomes more complex.

+1
source

Source: https://habr.com/ru/post/1479358/


All Articles