I am trying to iterate through elements of a struct, look for strings that include the format {...}
, and replace them with a corresponding string from a hash. This is the data I'm using:
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
This results in request.user == "first first"
. Trying parameters[match]
results in nil
.
Can anyone assist solving this?
The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match if any of the following conditions is true: If the replacement string cannot readily be specified by a regular expression replacement pattern.
The Java string replace() method will replace a character or substring with another character or string. The syntax for the replace() method is string_name. replace(old_string, new_string) with old_string being the substring you'd like to replace and new_string being the substring that will take its place.
For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.
Definition and Usage The \f metacharacter matches form feed characters.
Neither of your attempt will work because arguments of gsub!
are evaluated prior to the call of gsub!
. parameters[...]
will be evaluated prior to replacement, so it has no way to reflect the match. In addition, "\1"
will not be replaced by the first capture even if that string was the direct argument of gsub!
. You need to escape the escape character like "\\1
". To make it work, you need to give a block to gsub!
.
But instead of doing that, try to use what already is there. You should use string format %{}
and use symbols 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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With