【问题标题】:How can I replace words in a string with elements in an array in ruby?如何用ruby中的数组中的元素替换字符串中的单词?
【发布时间】:2021-12-07 15:41:54
【问题描述】:

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

"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-rails regex ruby string hash


    【解决方案1】:

    你可以使用

    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 demo详情

    • \{\{(?:width|length)\}\} - 匹配的正则表达式
      • \{\{ - {{ 子字符串
      • (?:width|length) - 匹配 widthlength 单词的非捕获组
      • \}\} - }} 子字符串
    • gsub 将字符串中所有出现的地方替换为
    • h - 用作第二个参数,允许将找到的与哈希键相等的匹配替换为相应的哈希值。

    您可以使用不带{} 的更简单的哈希定义,然后在正则表达式中使用捕获组来匹配lengthwidth。那你需要

    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]] }
    

    this Ruby demo。因此,这里使用(width|length) 代替(?:width|length),并且只有Group 1 用作块内h[Regexp.last_match[1]] 中的键。

    【讨论】:

    • 更简单地说,gsub 可以将散列作为第二个参数,结构为 {match => replacement},例如s.gsub(/\{\{(?:width|length)\}\}/,h) #=> "The dimension of the square is 10 and 20"
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-21
    • 1970-01-01
    • 2017-05-14
    • 1970-01-01
    • 2012-09-13
    • 2019-11-06
    相关资源
    最近更新 更多