How can I escape single and double quotes in a string?
I want to escape single and double quotes together. I know how to pass them separately but don\'t know how to
My preferred way is to not worry about escaping and instead use %q
, which behaves like a single-quote string (no interpolation or character escaping), or %Q
for double quoted string behavior:
str = %q[ruby 'on rails" ] # like single-quoting
str2 = %Q[quoting with #{str}] # like double-quoting: will insert variable
See https://docs.ruby-lang.org/en/trunk/syntax/literals_rdoc.html#label-Strings and search for % strings
.
I would use just:
str = %(ruby 'on rails ")
Because just %
stands for double quotes(or %Q) and allows interpolation of variables on the string.
Here is an example of how to use %Q[]
in a more complex scenario:
%Q[
<meta property="og:title" content="#{@title}" />
<meta property="og:description" content="#{@fullname}'s profile. #{@fullname}'s location, ranking, outcomes, and more." />
].html_safe
I would go with a heredoc if I'm starting to have to worry about escaping. It will take care of it for you:
string = <<MARKER
I don't have to "worry" about escaping!!'"!!
MARKER
MARKER delineates the start/end of the string. start string on the next line after opening the heredoc, then end the string by using the delineator again on it's own line.
This does all the escaping needed and converts to a double quoted string:
string
=> "I don't have to \"worry\" about escaping!!'\"!!\n"
>> str = "ruby 'on rails\" \" = ruby 'on rails"
=> "ruby 'on rails" " = ruby 'on rails"
Here is a complete list:
From http://learnrubythehardway.org/book/ex10.html