Using a regular expression to replace parameters in a string

I am trying to iterate through structure elements, look for lines that include the {...} format, and replace them with the corresponding hash line. This is the data I use:

 Request = Struct.new(:method, :url, :user, :password) request = Request.new request.user = "{user} {name}" request.password = "{password}" parameters = {"user" => "first", "name" => "last", "password" => "secret"} 

This is attempt 1:

 request.each do |value| value.gsub!(/{(.+?)}/, parameters["\1"]) end 

In this attempt, parameters["\1"] == nil .

Attempt 2:

 request.each do |value| value.scan(/{(.+?)}/) do |match| value.gsub!(/{(.+?)}/, parameters[match[0]]) end end 

The result is request.user == "first first" . An attempt to parameters[match] results in nil .

Can anyone help to resolve this issue?

+7
ruby regex
source share
2 answers

None of your attempts will work, because the arguments are gsub! evaluated before calling gsub! . parameters[...] will be evaluated before replacement, so it will not be able to reflect the match. Also, "\1" will not be replaced with the first capture, even if this line is a direct argument to gsub! . You need to avoid the escape character, for example, "\\1 ". To make it work, you need to select the gsub! block gsub! .

But instead, try to use what is already there. You must use the format of the string %{} and use characters for the hash.

 request.user = "%{user} %{name}" request.password = "%{password}" parameters = {user: "first", name: "last", password: "secret"} request.each do |value| value.replace(value % parameters) end 
+5
source share

You can use gsub with a block.

 request.each do |e| e.gsub!(/{.+?}/) { |m| parameters[m[1...-1]] } if e end 
+1
source share

All Articles