首页 > 解决方案 > 如何用ruby中的数组中的元素替换字符串中的单词?

问题描述

我正在尝试用数组中的相应值替换字符串中的单词(更一般地说是字符序列)。一个例子是:

"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-on-railsregexrubystringhash

解决方案


您可以使用

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- 用作第二个参数,允许用相应的哈希值替换找到的与哈希键相等的匹配项。

{您可以使用不带and的更简单的哈希定义},然后在正则表达式中使用捕获组来匹配lengthor 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]]块内的键。


推荐阅读