Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most elegant way in Ruby to substitute '?' in string with values in array

I have the following variables:

query = "(first_name = ?) AND (country = ?)" # string
values = ['Bob', 'USA'] # array

I need the following result:

result = "(first_name = Bob) AND (country = USA)" # string

The number of substitutions varies (1..20).

What is the best way to do it in Ruby?

like image 654
dpaluy Avatar asked Jan 19 '26 10:01

dpaluy


1 Answers

If you don't mind destroying the array:

query.gsub('?') { values.shift }

Otherwise just copy the array and then do the replacements.

Edited: Used gsub('?') instead of a regex.