我要转换字符串:
"{john:123456}"
到:
"<script src='https://gist.github.com/john/123456.js'>"
我写了一个可行的方法,但它非常愚蠢。是这样的:
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
有没有办法像下面的cool_method
那样做到这一点?
"{john:123}".cool_method(/{([a-zA-Z0-9\-_]+):(\d+)}/, "<script src='https://gist.github.com/$1/$2.js'></script>")
最佳答案
那个很酷的方法是 gsub。你离得太近了!只需将 $1 和 $2 更改为\\1 和\\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>")
关于ruby - 如何引用ruby正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16399829/