【问题标题】:Ruby gsub with different substitutions具有不同替换的 Ruby gsub
【发布时间】:2014-04-08 17:51:38
【问题描述】:

我有一个这样的字符串

I run the "(.*)" query from the "(.*)" file

我有一个包含这些值的数组,['process_date', 'dates']

我需要将其中的值替换到我的字符串中,就像这样

I run the "process_date" query from the "dates" file.

原来我是这样的

selected_item = selected_item.gsub(/\(\.\*\)/, input_value).rstrip

但现在我需要修改它以使用任意数量的输入。

任何帮助将不胜感激。

谢谢!

【问题讨论】:

    标签: ruby regex gsub


    【解决方案1】:

    如果您将块传递给gsub 而不是替换字符串,则每次匹配都会被yielded 到,其结果将用作替换字符串。您可以在该块中为值数组增加一个索引,并从该块中返回索引值:

    input_values = ['process_date', 'dates']
    i = -1
    selected_item =
      selected_item.gsub(/\(\.\*\)/) {
        i += 1
        input_values[i]
      }.rstrip
    

    或者,如果您不关心清空 input_values 数组,您可以使用 shift

    selected_item = selected_item.gsub(/\(\.\*\)/) { input_values.shift }.rstrip
    

    【讨论】:

    • 第二个对我来说效果很好,因为我根据输入参数的数量填充了该数组。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-12-26
    • 1970-01-01
    • 2021-08-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-02-01
    相关资源
    最近更新 更多