我試圖用陣列中的相應值替換字串中的單詞(更一般的字符序列)。一個例子是:
"The dimension of the square is {{width}} and {{length}}"與陣列[10,20]應該給
"The dimension of the square is 10 and 20"
我曾嘗試使用 gsub 作為
substituteValues.each do |sub|
value.gsub(/\{\{(.*?)\}\}/, sub)
end
但我無法讓它作業。我還考慮過使用散列而不是陣列,如下所示:
{"{{width}}"=>10, "{{height}}"=>20}. 我覺得這可能會更好,但同樣,我不確定如何編碼(ruby 新手)。任何幫助表示贊賞。
uj5u.com熱心網友回復:
您可以使用
h = {"{{width}}"=>10, "{{length}}"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(?:width|length)\}\}/, h)
# => The dimension of the square is 10 and 20
請參閱Ruby 演示。詳情:
\{\{(?:width|length)\}\}- 匹配的正則運算式\{\{- 一個{{子串(?:width|length)- 匹配width或length單詞的非捕獲組\}\}- 一個}}子串
gsub將字串中出現的所有內容替換為h- 用作第二個引數,允許用相應的散列值替換找到的與散列鍵相等的匹配項。
你可以用簡單一點的散列定義不{和},然后使用捕獲組在正則運算式匹配length或width。那么你需要
h = {"width"=>10, "length"=>20}
s = "The dimension of the square is {{width}} and {{length}}"
puts s.gsub(/\{\{(width|length)\}\}/) { h[Regexp.last_match[1]] }
請參閱此 Ruby 演示。因此,這里(width|length)使用,而不是(?:width|length)并且僅使用 Group 1 作為h[Regexp.last_match[1]]塊內部的鍵。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/328602.html
