Question

I have a string like this

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

And I have an array with these values in it, ['process_date', 'dates']

And I need to substitute the values in it into my string so it's like this

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

Originally I had it like this

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

But now I need to modify it to work with any number of inputs.

Any help would be appreciated.

Thanks!

Was it helpful?

Solution

If you pass a block to gsub instead of a replacement string, it will be yielded to for each match, and its result will be used as the replacement string. You can, in that block, increment an index into your array of values, and return the indexed value from the block:

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

Or if you don't care about emptying the input_values array, you could just use shift:

selected_item = selected_item.gsub(/\(\.\*\)/) { input_values.shift }.rstrip
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top