我想转换字符串:
"{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>")