Open In App

How to Escape single and double quotes in a string in Ruby?

Last Updated : 08 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

To handle strings containing single or double quotes in Ruby is not simple since putting these characters themselves within the string may also present difficulties. Your codes can give a syntax error or work in a way unintended just because of unescaped quotes. Luckily, Ruby has different ways to escape these symbols inside the text. This article will delve into three common methods to Escape single and double quotes in a string.

Using Backslashes (\):

Backslashes (\) are used as escape characters in Ruby strings. Using a backslash before a character, it tells Ruby that this character should be interpreted differently. In order to put single or double quotes into a string, you have to precede them with a backslash.

Example:

Ruby
string_with_single_quote = 'She said \'Hello\''
string_with_double_quote = "He said \"Hi\""

puts string_with_single_quote
puts string_with_double_quote

Output
She said 'Hello'
He said "Hi"

Using Alternate Quoting Syntax:

Other alternate quoting syntaxes supported by Ruby include %q{} for single quotes and %Q{} for double ones. In this case, we don’t need escaping quotations inside brackets.

Example:

Ruby
string_with_single_quote = %q{She said 'Hello'}
string_with_double_quote = %Q{He said "Hi"}

puts string_with_single_quote
puts string_with_double_quote

Output
She said 'Hello'
He said "Hi"

Using Here Documents:

Here Documents enable one to define multiple line strings. They start with << followed by a delimiter, usually a string or identifier format. A Here Documents does not interpret escape sequences so you can include single or double quotes without an escape sequence.

Example:

Ruby
string_with_single_quote = <<~STR
  She said 'Hello'
STR

string_with_double_quote = <<~STR
  He said "Hi"
STR

puts string_with_single_quote
puts string_with_double_quote

Output
She said 'Hello'
He said "Hi"

Conclusion:

Thus, all these methods will give the desired output, choosing them depends upon specific use case and user’s coding style.


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads