2013-05-06 69 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不是通过正则表达式进行解析的简单格式,当值更改或数据字符串变得更复杂时,可能会导致错误。