2012-12-13 264 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] }