The Ruby Basics – Strings

A String is one of the basic data types included in ruby, it is comprised of a collection of textual characters that may contain digits, letters, symbols and empty characters usually referred to as white space.

> String

Strings can be surrounded by single quotes or double quotes, essentially “Hello, World!” is the same as ‘Hello, World’ in this context.

Thinking of possible scenarios, what will happen if a quote is actually be contained within the string?

“Hello, ” World!” this looks quite odd, ‘Hello, ‘ World!’ this is sort of the same.

To handle this possible cases Ruby defines an escape character ( \ ) without the brackets.

“Hello, \” World!” well  this looks odd as well but it will work! ‘Hello, \’ World!’ .

Wait, since a string really begins and ends with a type of quote just a single quote or a double quote could we use double quotes in case a single quote will be used in the string and vice versa?

Of course!

“Hello, ‘ World!” well  this looks odd as well but it will work! ‘Hello, ” World!’ .

Single quotes and double quotes have other differences, double quotes allow something called string interpolation. Interpolation is a process that allows expressions to be defined and executed directly into Strings.

Lets create a statement that prints the class using interpolation.

> The class of ‘Class’ is String

Usually interpolation is used to incorporate and evaluate expressions when used in conjunction with Strings.

The basic syntax is: #{ruby expression goes here}

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.