Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Single-Quoted String Literal in Ruby
3.
Double-Quoted String Literal in Ruby
4.
Unicode Escapes
5.
Arbitrary delimiters for string literals
6.
Here documents
7.
Backtick command execution
8.
Mutability and String Literal in Ruby
9.
The String.new method
9.1.
String.new vs String Literal
10.
Frequently Asked Questions
10.1.
Is it possible to iterate over a string literal in Ruby?
10.2.
Is String Literal in Ruby Mutable?
10.3.
In Ruby, what does each_char do?
10.4.
In Ruby, how do you append to a string?
10.5.
What is Ruby primarily used for?
10.6.
Is Ruby still utilized in today's world?
11.
Conclusion
Last Updated: Mar 27, 2024

String literal in Ruby

Author Shiva
0 upvote
Master Python: Predicting weather forecasts
Speaker
Ashwin Goyal
Product Manager @

Introduction

String objects are used to store ordered sequences of bytes, usually characters, that are used to create human-readable text. String objects are a common object type in all programming languages, and Ruby provides a number of high-level and low-level methods for creating, accessing, and manipulating them.

String literals are the most common way to produce strings. In Ruby, a literal is a particular syntax that generates an object of a certain type. 23 is a literal that constructs a Fixnum object, for example. There are various types of string literal.

Single-Quoted String Literal in Ruby

Single quotes are used to enclose the simplest string literal in Ruby (the apostrophe character).

The value of the string is the text enclosed in quotation marks:

'This is a simple string literal in Ruby'

 

If you need to use an apostrophe within a single-quoted string literal, use a backslash to prevent the Ruby interpreter from thinking the string is finished:

'Won\'t you solve more problems?'

 

The backslash also serves as an escape character for another backslash, preventing the second backslash from being regarded as an escape character. Here are some examples of when a double backslash is required:

'This string literal in ruby ends with a single backslash: \\'
'This is a backslash-quote: \\\''
'Two backslashes: \\\\'

 

A backslash in a single-quoted string has no particular meaning if the character after it is not a quotation or a backslash. In most cases, backslashes in string literals do not need to be doubled (but they can be). The following two string literal, for example, are equivalent:

'a\b' == 'a\\b'

 

Single-quoted strings can span multiple lines, and the newline characters are included in the resulting string literal. With a backslash, you can't get rid of the newlines:

'This is a long string literal in ruby \
that includes a backslash and a newline'

 

Simply break a large single-quoted string literal across numerous lines without embedding newlines; the Ruby interpreter will concatenate them during the parsing process. However, you must escape newlines between literals. So, that Ruby does not view the newline as a statement terminator:

message =
'These three literals are '\
'concatenated into one by the interpreter. '\
'The resulting string contains no newlines.'
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

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 DSACompetitive Programming, JavaScriptSystem 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!

Next article
String Interpolation with sprintf in Ruby
Live masterclass