2013-05-06 65 views
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>") 
+2

如果這是從某處來的JSON,我只使用JSON。雖然正則表達式的解決方案「很好」,但我仍然會考慮將分割和索引所產生的值。 – 2013-05-06 13:50:32

+1

+1 @DaveNewton。傳入的數據字符串是JSON,因此第一步是將其重新轉換爲其對象形式,然後對其進行按摩。用正則表達式解析JSON可能會造成嚴重的後果。在散列或數組中進行按摩是不太可能發生的。 – 2013-05-06 15:41:04

+0

是否總是隻有一個名稱/值,或者可以接收多個條目?而且,是字符串'「{john:123456}」,還是真的是'{「john」:123456}'? – 2013-05-06 15:51:25

回答

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>") 
+2

class String;別名:cool_method:gsub;結束,:) – 2013-05-06 13:49:33

+0

@Shawn:謝謝你的好意,我想我應該學習更多ruby-basic,向你致以最誠摯的問候。 – boostbob 2013-05-06 14:13:28

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瞭解更多詳情。

+1

爲什麼要爲這種專門的方法打開String類? – Shoe 2013-05-06 13:44:00

+0

我wouldnt或者但使用字符串插值是真正的方式去這裏。 – 2013-05-06 13:45:48

+0

@ Jueecy.new OP的'convert'看起來像是String類的成員函數。無論如何,我認爲肖恩的回答更好。 – 2013-05-06 13:54:28

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'>" 
+0

感謝你的代碼,我知道掃描和each_with_object方法可以一起工作。最好的問候給你。 – boostbob 2013-05-06 14:02:02

1

這看起來像一個JSON字符串,因此,作爲@DaveNewton說,把它當作一個:

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>" 

爲什麼不把它當作一個字符串並在其上使用正則表達式呢?因爲JSON不是通過正則表達式進行解析的簡單格式,當值更改或數據字符串變得更復雜時,可能會導致錯誤。