2013-03-19 54 views
0

给定的字符串正确的密钥和值我有一个列表:如何解析为使用Ruby

key1:this is an{example{of an example}I like} key2:this is another example key3: this is secondary{example{of an example}} 

我需要单独的钥匙,通过差异比较键的值,所以结果我想获得是:

{ 
    :key1 => 'this is an [example[of an example]I like]', 
    :key2 => 'this is another example', 
    :key3 => 'this is secondary[example[of an example]]' 
} 

是这样或类似的东西可能与Ruby或正则表达式?

+0

你想返回什么?哈希?一个字符串? – Mischa 2013-03-19 14:42:15

+0

我希望它是散列。我目前试图使用拆分和正则表达式除以“:”和“{}”,就我所知 – lifejuggler 2013-03-19 14:51:12

+0

我编辑了你的问题,以便所需的返回值看起来像一个散列。目前还不清楚你的所有方括号是什么意图。随时再次编辑,以明确。 – Mischa 2013-03-19 15:08:11

回答

0

你去那里:

def parse_into_hash(s) 
    keys = s.scan(/\w+:/.map{|k| k.chomp(":")} 
    values = s.split(/\w+:/).select(&:present?) 
    Hash[keys.zip values] 
end 

这不是防弹。如果冒号中有冒号,或者其中任何值为空字符串,它可能会失败,但它对您的示例有效,并且会让您开始。如果你需要,你可以使它更强大。

+0

谢谢!我将以你的榜样为基础 – lifejuggler 2013-03-21 14:10:28