ruby-on-rails - 如何用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}
. 我觉得这可能会更好,但我不知道如何编码(红宝石新手)。任何帮助表示赞赏。
解决方案
您可以使用
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的更简单的哈希定义}
,然后在正则表达式中使用捕获组来匹配length
or 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]]
块内的键。
推荐阅读
- serenity-platform - 如何在网格中动态修改快速过滤器处理程序?
- typescript - 在打字稿中验证数字和枚举的联合类型
- javascript - 将基数转换为字母 JavaScript
- go - GoLang 运行“bundle”:exec:“bundle”:$PATH 中找不到可执行文件
- raspberry-pi - 如何在 proteus 中使用树莓派控制电机
- macos - 无法在 MACOSX 上使用 USB 设备启动 docker 映像
- angular - 是否可以在 fullcalendar(Angular) 中仅编辑一个重复/重复事件的事件?
- linux - 我应该在 Windows 或 Docker 命令行上运行 Docker 命令吗?
- javascript - 如何使用 chartjs 3.2.0 显示 A2、B2、C2 标签?
- c - 调用 fork() 时子进程执行了哪部分代码?