我试图用数组中的相应值替换字符串中的单词(更一般的字符序列)。例如:
"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新手)。如有任何帮助,不胜感激。
可以使用
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)}}
-匹配的正则表达式{{
- a{{
子字符串(?:width|length)
—匹配width
或length
字的非捕获组}}
-}}
子字符串
gsub
用 替换字符串中的所有出现h
-用作第二个参数,允许用相应的哈希值替换与哈希键相等的匹配项。
您可以使用稍微简单一点的散列定义,不包含{
和}
,然后在regex中使用捕获组来匹配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)
,并且只使用组1作为块内h[Regexp.last_match[1]]
中的键。