Double-Quoted String Literal in Ruby
Single quoted literals are substantially more versatile than string literals delimited by double quotation marks. Backslash escape sequences supported by double-quoted literals include n for newline, t for tab, and " for a quotation mark that does not end the string:
"\t\"This quote begins with a tab and ends with a newline\"\n"
"\\" # A single backslash
Arbitrary expressions can also be included in double-quoted string literals in Ruby. The expression is evaluated, transformed to a string, and added to the string in place of the expression text itself when the string is generated.
String interpolation is the Ruby term for replacing an expression with its value. In double-quoted strings, expressions begin with the # character and are enclosed in curly braces:
"180 degrees=#{2*Math::PI} radians" # "180 degrees=3.1415 radians"
Double-quoted string literal in ruby may span multiple lines, and line terminators become
part of the string literal, unless escaped with a backslash:
"This string literal
has two lines \
but is written on three"
If you want to impose network CRLF (Carriage Return Line Feed) line terminators, such as those used in the HTTP protocol, you can explicitly encode the line terminators in your strings. To accomplish this, write all of your string literals on a single line and use the r and n escape sequences to explicitly include the line endings. Remember that neighboring string literals are automatically concatenated, but the newline between them must be escaped if they are written on separate lines:
"This string has three lines.\r\n" \
"It is written as three adjacent literals\r\n" \
"separated by escaped newlines\r\n"
Unicode Escapes

With \u escapes, arbitrary Unicode characters can be included in double-quoted strings in Ruby 1.9. \u is followed by exactly four hexadecimal digits (letters can be upper- or lowercase) that constitute a Unicode codepoint between 0000 and FFFF in its most basic form. Consider the following scenario:
"\u20ac" # => "€"
An open curly brace, one to six hexadecimal digits, and a close curly brace follow a second variant of the \u escape. Leading zeros can be dropped in this form, and the digits between the braces can represent any Unicode codepoint between 0 and 10FFFF:
"\u{A5}" # => "¥": same as "\u00A5"
Arbitrary delimiters for string literals
It's tough to utilize single- and double-quoted string literals when working with text that incorporates apostrophes and quotation marks. For string literals, Ruby has a generalized quoting syntax. The percent q sequence starts a string literal that follows single-quoted string rules, while the % Q (or just %) sequence starts a string literal that follows double-quoted string rules. The delimiter character comes after q or Q, and the string literal continues until it finds a matching (unescaped) delimiter. The concluding delimiter is otherwise identical to the opening delimiter. Some instances are as follows:
%q(Don't worry about escaping ' characters!)
%Q|"How are you?", he said|
%-This string literal ends with a newline\n-
Here documents
The syntax is the << symbol, followed by an end marker, then zero or more lines of text, and finally the same end marker on a line by itself:
str = <<HERE
This is a simple string
HERE
It's worth noting that here documents can be "stacked"; for example, here's a function call that receives three such strings:
method_name(<<STRING1, <<STRING2, <<STRIKNG3)
first string!
STRING1
second string!
STRING2
third string!
STRING3
By default, a here-document behaves as a double-quoted string, with its contents subject to escape sequence interpretation and embedded expression interpolation. The here-document, on the other hand, operates like a single-quoted string if the end marker is single-quoted:
str = <<'EOF'
This isn't a tab: \t
and this isn't a newline: \n
*EOF
It's important to note that the only place you can include a comment in a here document is on the first line, after the token and before the literal.
Backtick command execution
Another syntax utilizing quotes and strings is supported by Ruby. When text is encased in backquotes, it is considered a double-quoted string literal. The value of the literal is supplied to the Kernel.' method, which is named after it. This method runs the text as a shell command on the operating system and returns the command's output as a string.
Consider the Ruby code below:
`ls`
These four characters on a Unix system produce a string that lists the names of the files in the current directory.
Backticks can be replaced with a generalized quotation syntax in Ruby. This is similar to the percent Q syntax from previously, but instead uses % x (execute):
%x[ls]
The text within the backticks (or after % x) is treated as a double-quoted literal, allowing for the interpolation of arbitrary Ruby expressions into the string.
Mutability and String Literal in Ruby
In Ruby, strings can be changed. As a result, the Ruby interpreter cannot represent two identical string literals with the same object. (If you're a Java programmer, this may come as a shock.) Ruby builds a new object each time it encounters a string literal. Ruby will construct a new object for each iteration if you include a literal in the loop body. You can see this for yourself by doing the following:
10.times { puts "test".object_id }
For efficiency, you should avoid using literal within loops.
The String.new method
You can use the String.new method to construct new strings in addition to the string literal in ruby alternatives outlined above. This method returns a newly formed string with no characters if no arguments are provided. It produces and returns a new String object with a single string parameter that reflects the same text as the argument object.
String.new vs String Literal
String literals can now be frozen starting with Ruby 2.3. It's Ruby 3.0's planned default, which means...
x = "Hello"
x.upcase!
# Because the string is immutable, this will result in an error.
# But with the help of constructor it will work fine.
x = String.new("Hello")
x.upcase!
Frequently Asked Questions
Is it possible to iterate over a string literal in Ruby?
The chars method can be used to turn a string into an array of characters. Then you can iterate over this array by using each.
Is String Literal in Ruby Mutable?
The []= method in Ruby can be used to modify a portion of a string. To use this function, simply supply the string of characters to be replaced and assign the new string to the method.
In Ruby, what does each_char do?
Each character that makes up a string is passed to a block in Ruby using the each_char function. each_char is a single argument block that represents characters in a string.
In Ruby, how do you append to a string?
To append a string to another, use the + operator.
Eg. a + b + c creates a new string.
What is Ruby primarily used for?
The language has a wide range of applications, including web scraping, static site generation, command-line tools, automation, DevOps, and data processing.
Is Ruby still utilized in today's world?
Despite the fact that Ruby on Rails was first released about 18 years ago, the framework is still frequently utilized among professional developers.
Conclusion
This article covers everything you need to know about String Literals in Ruby. Want to learn more?
Here are more articles for rescue.
Check out this problem - Multiply Strings
Refer to our guided paths on Coding Ninjas Studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses and refer to the mock test and problems available. Take a look at the interview experiences and interview bundle for placement preparations.
Do upvote our blog to help other ninjas grow.
Happy Learning!
