Home » Ruby » Escaping single and double quotes in a string in ruby?

Escaping single and double quotes in a string in ruby?

Posted by: admin November 30, 2017 Leave a comment

Questions:

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 pass both of them.

e.g: str = "ruby 'on rails" " = ruby 'on rails"

Answers:

My preferred way is to not worry about the escaping and using %q (which acts like a single quoted string) or %Q for double quoted string behavior.

so

str = %q[ruby 'on rails"] # Single quoting
str2 = %Q[quoting with #{str}] # will insert variable

Questions:
Answers:

Use backslash to escape characters

str = "ruby \'on rails\" "

Questions:
Answers:

You can use Q strings which allow you to use any delimiter you like:

str = %Q|ruby 'on rails" " = ruby 'on rails|

Questions:
Answers:

Here is a complete list:

enter image description here

From http://learnrubythehardway.org/book/ex10.html

Questions:
Answers:
>> str = "ruby 'on rails\" \" = ruby 'on rails"
=> "ruby 'on rails" " = ruby 'on rails"

Questions:
Answers:

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"

Questions:
Answers:

I would use just:

str = %(ruby 'on rails ")

Because just % stands for double quotes(or %Q) and allows interpolation of variables on the string.

Questions:
Answers:

One caveat:

Using %Q[] and %q[] for string comparisons is not intuitively safe.

For example, if you load something meant to signify something empty, like "" or '', you need to use the actual escape sequences. For example, let’s say qvar equals "" instead of any empty string.

This will evaluate to false
if qvar == "%Q[]"

As will this,
if qvar == %Q[]

While this will evaluate to true
if qvar == "\"\""

I ran into this issue when sending command-line vars from a different stack to my ruby script. Only Gabriel Augusto’s answer worked for me.

Questions:
Answers:

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