Strings in Ruby featured image

Working with Strings in Ruby

Ruby is an interpreted, dynamic, reflective, object-oriented programming language. Developed by Yukihiro Matsumoto, Ruby focuses on simplicity and productivity. The elegant syntax allows developers to read and write code easier.

In this guide, we will be working with strings in Ruby.

Prerequisites

To perform the steps demonstrated in this tutorial, you need the following components:

The String Data Type

In programming, a string is a common data type that every modern programming language supports. It’s characterized by a sequence of characters. The entire character sequence is treated as a single piece of data. A string may contain alphabets, digits, and special characters/symbols.

Ruby, being a pure object-oriented programming language, treats strings as objects. Unlike many other languages, strings in Ruby are mutable. Basically, the string value can be changed in-place.

Step 1 – Creating and Printing Strings

In Ruby, strings are enveloped by either single quotes ( ') or double quotes ( "). The following are two valid strings in Ruby:

To print any output to the console screen, Ruby comes with the print method:

Time to put it in action. Create a new Ruby file practice.rb and enter the following codes:

Run the code:

Strings in Ruby 1

As expected, the print command prints the strings provided. If we want to print the strings on separate lines, it’s better to use puts instead. Update the code:

Next, run the code again:

Strings in Ruby 2

Step 2 – String Variables

Variables are names referring to a specific place in the computer memory where a value is stored. We can store the desired value in the variable and use it later.

In Ruby, to declare a string variable, define the variable name and assign a string value:

Write the following code in practice.rb:

Run the code:

Here:

  • We’ve defined two variables first_half and second_half, each assigned a string value.
  • The puts method prints the value of the variables.

Step 3 – String Concatenation

By concatenating, we can take multiple strings and join them together to create a new string. String concatenation is denoted by the concatenation operator ( +). Note that this symbol is also the addition operator when working with arithmetic operations.

Let’s try performing string concatenation on the strings we’ve declared so far:

Run the code:

As the output showcases, concatenation doesn’t introduce any additional character in-between the strings. That’s why fox and jumps are both lumped together. We can fix it by introducing whitespace after fox:

Run the code:

Now the output looks better.

String concatenation also works with variables. Have a look at the following example:

Strings in Ruby 3

Run the code:

The next example demonstrates a long chain of concatenation:

Strings in Ruby 4

Run the code:

So far, we’ve only dealt with string variables. What if there were different variable types? The following program tests out this scenario:

Strings in Ruby 5

When trying to run this program, Ruby will throw an error message:

However, we can convert the integer to a string to avoid this issue:

Strings in Ruby 6

Here:

  • The method to_s converts the variable value to a string.

Converting numbers to strings is a common occurrence when dealing with elements like zip codes, currency, phone numbers, and other numerical data.

Step 4 – String Interpolation

While string concatenation is a powerful feature, it can become tricky very easily. In many situations, you’ll probably find yourself missing a concatenation operator ( +), leading to a big headache. Moreover, when dealing with different data types, it has to be converted to a string first. Thankfully, Ruby offers other ways of injecting variable values to a string using the feature string interpolation.

Here’s what it looks like. For example, instead of using:

We will be using:

While the syntax may look a little bit weird, it dramatically simplifies the code. No need to manually call the to_s method for converting the variable value to string.

Let’s use this new technique to update our previous code:

Strings in Ruby 7

Run the code:

Step 5 – String Literals and String Values

Notice that strings declared in the codes are always surrounded by quotes. However, when printing the output to the console screen, there are no quotation symbols. There’s clearly a distinction between them.

  • String literal: It’s the string written in the source code (including the quotations).
  • String value: It’s the value that’s printed on the output (without the quotations).

For example, the following one is a string literal:

The string value of it would be hello world.

Step 6 – Escaping Quotes and Apostrophes

As we demonstrated, quotes and apostrophes are used for denoting strings in the source code. This poses a problem: you can’t have them directly on the string. Otherwise, it will cause issues. The following code demonstrates this:

Strings in Ruby 8

There are different tactics to circumvent this issue.

  • Using Alternate String Syntax

This is the simplest way of getting around the issue. If your string needs single quotes, then use double quotes in string literal (and vice-versa).

Let’s fix the previous example:

Another example would be:

However, it’s not going to work in every situation. For example:

  • Using Escape Characters

The backslash ( \) character is often referred to as the escape character. It prevents Ruby from interpreting the next character literally. Let’s fix the previous example. Use the backslash to prevent Ruby from interpreting the internal double quotations as literals:

  • Using Alternate Syntax

So far, we’ve only been working with single and double quotations to denote the string literal. However, the previous examples are simple demonstrations of how this can get out of hand very quickly. To solve this issue, we can ditch the quotation marks altogether and use a completely different symbol to denote the start and end of a string.

Have a look at the following example:

Here:

    • The symbol % defines the next character ( $, in this case) as the delimiter of the string.
    • The string literal here is $the quick brown fox said, "I jumped over the lazy dog"$.

Let’s put it into action:

Here, the string is basically treated as the following:

However, it re-introduces the problem of escaping the delimiter if it’s used in the string. One way of avoiding it is using symbols that generally don’t appear on strings. Such symbols could include curly braces, square brackets, etc.:

It also works perfectly with string interpolations:

It’s also common to use %Q{} and %q{} to define strings in Ruby programs. Here, %Q{} acts like double quotations and %q{} acts like single quotations.

Step 7 – Newlines and Long Strings

When working with strings, there will be situations when you’d want to introduce a newline or carriage return in the string. We can do so by introducing the escape characters \n (newline) and \r (carriage return).

Have a look at the following example:

The string literal looks confusing, right? Let’s re-arrange it for better readability:

Instead of manually declaring the newline characters, we can also use the following structure:

Strings in Ruby 8

Strings in Ruby 9

In this method, the string preserves all the whitespaces. However, this scuffs the output. Remove the extra whitespaces to fix it:

Strings in Ruby 10

While the whitespace issue was fixed, it reduces the readability of the code. We can fix this issue by implementing a heredoc, a term for multi-line string literals. The updated code would look like this:

Strings in Ruby 11

Strings in Ruby 12

Starting from Ruby v2.3 and above, there’s another feature available, named squiggly heredoc syntax. It removes the leading whitespace in the strings. To express a squiggly heredoc, replace the hyphen ( -) with a tilde ( ~):

Strings in Ruby 13

Step 8 – Replicating Strings

In some situations, it may be necessary to repeat a string several times. Ruby allows replicating strings in various ways.

One such technique is using the * operator. Generally, it’s used as the multiplication operator when dealing with numbers. When dealing with strings, however, it becomes the string replication operator, repeating the single string as many times as necessary. The number of repetitions must be an integer.

In the following example, the text Boris is going to be repeated 5 times:

Strings in Ruby 14

Using this feature, we can produce some cool ASCII art. Check out the following example:

Final Thoughts

Strings, in programming, are quintessential. This guide demonstrates working with strings in Ruby. We learned how to create strings and perform various operations like concatenation, handling newlines, quotes, etc. Using string interpolation, we also learned how to better integrate variable values into strings. Using the string replication operator, we can also repeat a single string multiple times.

While Ruby, by itself, is an excellent programming language, it’s often combined with the Rails framework. Ruby on Rails is an open-source web app framework. Learn more about installing Ruby on Rails on Ubuntu. However, Ruby can also work with other apps, like MySQL and PostgreSQL.

Happy Computing!

About Hark Labs

Software Engineer and enthusiast about new technologies