Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby gsub doesn't escape single-quotes

People also ask

Can you use single quotes in Ruby?

Best practice. As most of the Ruby Linters suggest use single quote literals for your strings and go for the double ones in the case of interpolation/escaping sequences.

How do I bypass a single quote in JavaScript?

We can use the backslash ( \ ) escape character to prevent JavaScript from interpreting a quote as the end of the string. The syntax of \' will always be a single quote, and the syntax of \" will always be a double quote, without any fear of breaking the string.

How do you escape a single quote in curl command?

The backslash ( \ ) character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character.


\' means $' which is everything after the match. Escape the \ again and it works

"Yaho'o".gsub("'", "\\\\'")

"Yaho'o".gsub("'", "\\\\'")

Because you're escaping the escape character as well as escaping the single quote.


This will also do it, and it's a bit more readable:

def escape_single_quotes(str)
  str.gsub(/'/) { |x| "\\#{x}" }
end

If you want to escape both a single-quote and a backslash, so that you can embed that string in a double-quoted ruby string, then the following will do that for you:

def escape_single_quotes_and_backslash(str)
  str.gsub(/\\|'/) { |x| "\\#{x}" }
end