【问题标题】:An efficient way of custom tag parsing in rubyruby中自定义标签解析的一种有效方法
【发布时间】:2012-12-01 03:05:09
【问题描述】:

我有一个像这样的哈希:

{: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 次,并且每次解析一个标签。我不认为这是一个好的解决方案。有没有更好的解决办法?

【问题讨论】:

  • 只遍历字符串一次,多次查询hash。

标签: ruby


【解决方案1】:

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

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]}

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

【讨论】:

  • 太棒了。实际上,在您回复之前 5 分钟,我也在查看 ruby​​-doc 的 gsub。谢谢你。我选择了你的答案。
【解决方案2】:

看起来有一个解决方案取决于您使用的 ruby​​ 版本。对于 1.9.2,您可以使用哈希,如下所示:https://stackoverflow.com/a/8132638/1572626

不过,问题大体相似,因此请阅读其他 cmets:Ruby multiple string replacement

【讨论】:

    【解决方案3】:

    您可以将 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] }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-18
      • 1970-01-01
      相关资源
      最近更新 更多