2012-12-13 196 views
0

自定义标签解析一个有效的办法,我有一个像哈希:的红宝石

{:name => 'foo', :country => 'bar', :age => 22} 

我也有喜欢

Hello ##name##, you are from ##country## and your age is ##age##. I like ##country## 

使用上述哈希字符串,我要分析此字符串并替代具有相应值的标签。因此,解析后,字符串将如下所示:

Hello foo, you are from bar and your age is 22. I like bar 

您是否建议借助正则表达式来解析它?在这种情况下,如果我在散列中有5个值,那么我将不得不遍历字符串5次,每次解析一个标记。我不认为这是一个好的解决方案。有没有更好的解决方案?

+0

只有遍历字符串一次,查询哈希几次。 – halfelf

回答

3

这里是我的问题的解决方案:

h = {:name => 'foo', :country => 'bar', :age => 22} 
s = "Hello ##name##, you are from ##country## and your age is ##age##. I like ##country##}" 
s.gsub!(/##([a-zA-Z]*)##/) {|not_needed| h[$1.to_sym]} 

它通常使用正则表达式进行一次传递,并执行我认为您需要的替换。

+0

太棒了。实际上,在你回答之前5分钟,我也在查看ruby-doc的gsub。谢谢。我选择了你的答案。 – JVK

0

您可以用String#GSUB与块:

h = {:name => 'foo', :country => 'bar', :age => 22} 
    s = 'Hello ##name##, you are from ##country## and your age is ##age##. I like ##country##' 
    s.gsub(/##(.+?)##/) { |match| h[$1.to_sym] }