4

文字列を変換したい:

"{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>")
4

4 に答える 4

7

そのクールなメソッドは 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>")
于 2013-05-06T13:44:38.177 に答える
1

私はするだろう

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

詳細については、 http://ruby-doc.org/core-2.0/Regexp.html#label-Capturingを参照してください。

于 2013-05-06T13:42:46.023 に答える
1
s = "{john:123456}".scan(/\w+|\d+/).each_with_object("<script src='https://gist.github.com") do |i,ob|
  ob<< "/" + i
end.concat(".js'>")
p s #=> "<script src='https://gist.github.com/john/123456.js'>"
于 2013-05-06T13:46:51.807 に答える