cheeseandpepper cheeseandpepper - 1 year ago 51
Ruby Question

How can I escape " or ' when it is a variable in ruby or rails?

I'm building a js file on the backend for future use and need to convert macros into js code. My

in the method below was working fine until I had a url with double quotes. If I have a variable
quote_type = "'"
, how can I interpolate that as an escaped quote? In other words..


Here's my existing method and I just added the
variable to try this out.

def substitute_timestamp_macro!(string)
quote_type = string[0]
string.gsub('[timestamp]', '\' + new Date().getTime() + \'')

edit: example string would be

edit 2: Here is the expected result:
";time=" + new Date().getTime() + "?"

here is the actual result
";time=' + new Date().getTime() + '?"

notice in my
i hard coded an escaped single quote. I now want to use the variable to match the input quote so if it's single, use single, and if double, use double

Answer Source

Consider %() to wrap your string:

def substitute_timestamp_macro!(string)
  %("#{string}").gsub("[timestamp]", %(" + new Date().getTime() + "))

Note that this will render a string with escaped double quotes:

=> "\";time=\" + new Date().getTime() + \"?\""

Which will be interpreted properly when you render this to a buffer:

puts substitute_timestamp_macro!(";time=[timestamp]")
=> ";time=" + new Date().getTime() + "?"