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:
- A properly-configured Ubuntu system. Learn more about configuring your own Ubuntu server on CloudSigma.
- Any modern text editor, preferably with syntax highlighting, for example, VS Code, Sublime Text, Atom, Brackets, Vim, etc.
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:
1 2 |
'the quick brown fox' "jumps over the lazy dog" |
To print any output to the console screen, Ruby comes with the print method:
1 2 |
print 'the quick brown fox' print "jumps over the lazy dog" |
Time to put it in action. Create a new Ruby file practice.rb and enter the following codes:
Run the code:
1 |
ruby practice.rb |
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:
1 2 |
puts 'the quick brown fox' puts "jumps over the lazy dog" |
Next, run the code again:
1 |
ruby practice.rb |
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:
1 |
<variable_name> = <string> |
Write the following code in practice.rb:
1 2 3 4 |
first_half = 'the quick brown fox' second_half = "jumps over the lazy dog" puts first_half puts second_half |
Run the code:
1 |
ruby practice.rb |
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:
1 |
puts "the quick brown fox" + "jumps over the lazy dog" |
Run the code:
1 |
ruby practice.rb |
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:
1 |
puts "the quick brown fox " + "jumps over the lazy dog" |
Run the code:
1 |
ruby practice.rb |
Now the output looks better.
String concatenation also works with variables. Have a look at the following example:
1 2 |
first_half = "the quick brown fox " puts first_half + "jumps over the lazy dog" |
Run the code:
1 |
ruby practice.rb |
The next example demonstrates a long chain of concatenation:
1 2 3 |
username = "cloudsigma" fav_color = "blue" puts "hello, " + username + "! your favorite color is " + fav_color + "." |
Run the code:
1 |
ruby practice.rb |
So far, we’ve only dealt with string variables. What if there were different variable types? The following program tests out this scenario:
1 2 3 |
username = "cloudsigma" user_id = 20 puts username + user_id |
When trying to run this program, Ruby will throw an error message:
1 |
ruby practice.rb |
However, we can convert the integer to a string to avoid this issue:
1 2 3 |
username = "cloudsigma" user_id = 20 puts username + user_id.to_s |
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:
1 |
"hello, " + username + "!" |
We will be using:
1 |
"hello, #{username}!" |
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:
1 2 3 |
username = "cloudsigma" user_id = 20 puts "hello, #{username}! your user ID is #{user_id}" |
Run the code:
1 |
ruby practice.rb |
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:
1 |
"hello world" |
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:
1 |
puts 'it's what it is' |
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:
1 |
puts "it's what it is" |
Another example would be:
1 |
puts 'he said, "hello world"' |
However, it’s not going to work in every situation. For example:
1 |
puts "Clousdigma says, "I'm a happy boi!"" |
-
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:
1 |
puts "Cloudsigma says, \"I'm a happy boi!\"" |
-
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:
1 |
%$the quick brown fox said, "I jumped over the lazy dog"$ |
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:
1 |
puts %$the quick brown fox said, "I jumped over the lazy dog"$ |
Here, the string is basically treated as the following:
1 |
"the quick brown fox said, \"I jumped over the lazy dog\"" |
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.:
1 |
puts %{"hello, world!", he said} |
It also works perfectly with string interpolations:
1 2 3 |
username = "cloudsigma" user_id = 5 puts %{hello, #{username}.#{user_id}!} |
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:
1 2 |
hello_world = "the quick\nbrown fox\njumps over\nthe lazy dog" puts hello_world |
The string literal looks confusing, right? Let’s re-arrange it for better readability:
1 2 3 4 5 6 7 |
hello_world = "the quick\n" + "brown fox\n" + "jumps over\n" + "the lazy dog" puts hello_world |
Instead of manually declaring the newline characters, we can also use the following structure:
1 2 3 4 5 6 |
hello_world = "the quick brown fox jumps over the lazy dog" puts hello_world |
In this method, the string preserves all the whitespaces. However, this scuffs the output. Remove the extra whitespaces to fix it:
1 2 3 4 5 |
hello_world = "the quick brown fox jumps over the lazy dog" |
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:
1 2 3 4 5 6 7 8 |
hello_world = <<-END the quick brown fox jumps over the lazy dog END puts hello_world |
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 ( ~):
1 2 3 4 5 6 7 8 |
hello_world = <<~END the quick brown fox jumps over the lazy dog END puts hello_world |
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:
1 |
print "Boris" * 5 + "\n" |
Using this feature, we can produce some cool ASCII art. Check out the following example:
1 2 3 |
puts "=" * 15 puts "| hello world |" puts "=" * 15 |
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!
- How To Enable, Create and Use the .htaccess File: A Tutorial - March 8, 2023
- An Overview of Queries in MySQL - October 28, 2022
- Introduction to Cookies: Understanding and Working with JavaScript Cookies - October 25, 2022
- An Overview of Data Types in Ruby - October 24, 2022
- The Architecture of Iptables and Netfilter - October 10, 2022