1

I'm having trouble inserting an outside variable into a string using regular expressions.

I have a string which looks like:

    string = "7  -"

And I want to insert a integer as a string into the space between the "7" and the "-", and I've tried to use interpolation, like so:

    variable = "15"
    string = string.gsub(/(\S?\d+)(\s)(\s)(\D)/, '\1\2#{variable}\3\4')

(the \S? is to account for any " - " attached to a digit for whether it is positive or negative)

The output is a string looking like this:

    "7 \#{variable} -"

But I want the output to look like this:

    "7 15 -"

2 Answers 2

1

Here's an elegant solution to your problem:

s = "7  -"
v = 15
string = s.gsub(/\d\s/, "#{s.delete("-").strip} #{v}")
#=> "7 15 -"
Sign up to request clarification or add additional context in comments.

2 Comments

How would delete and strip work in this case? I'm having a tough time following along.
s.delete("-").strip is: delete is removing the hyphen and strip is removing the white space from the instance of s as is: s = "7 -" The space is returned to the string here: ...ip}_\s_#{v}" Understand?
0

Use double quote. Single-quoted string does not interpolate.

string = "7  -"
variable = "15"
string = string.gsub(/(\S?\d+)(\s)(\s)(\D)/, "\\1\\2#{variable}\\3\\4")
string # => "7 15 -"

1 Comment

Works like a charm, thanks! I'm just learning Ruby, and usually use double quotes. Is it best practice to use double quotes most times? Or just when dealing with regex?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.