2

How do I include a variable in the 'replace' portion of gsub?

replace.gsub(/#{year}","1/, '#{year}","b')

This outputs:

=> #{year}","b

Let's say year = 2013. I want it to output:

=> 2013","b
3
  • 5
    You need double quotes to do variable substitution, so replace '#{year}","b' with "#{year}\",\"b". Commented May 1, 2013 at 23:56
  • String interpolation between single quotes doesn't work in Ruby. I make that mistake all the time. Commented May 1, 2013 at 23:58
  • Thank you! I spent too long trying to figure that out. Commented May 2, 2013 at 0:00

1 Answer 1

1

Adding on to Blender's answer, you can use an alternate way of writing strings to avoid having to escape quotes:

replace.gsub(/#{year}","1/, %{#{year}","b})

where %{} is another way to write a string literal that you can do string interpolation in.

Sign up to request clarification or add additional context in comments.

Comments

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.