In this article by Jordan Hudgens, the author of the book Comprehensive Ruby Programming, you'll learn about the Ruby String data type and walk through how to integrate string data into a Ruby program. Working with words, sentences, and paragraphs are common requirements in many applications. Additionally you learn how to:
(For more resources related to this topic, see here.)
A string is a data type in Ruby and contains set of characters, typically normal English text (or whatever natural language you're building your program for), that you would write. A key point for the syntax of strings is that they have to be enclosed in single or double quotes if you want to use them in a program. The program will throw an error if they are not wrapped inside quotation marks.
Let's walk through three scenarios.
In this code I tried to simply declare a string without wrapping it in quotation marks. As you can see, this results in an error. This error is because Ruby thinks that the values are classes and methods.
In this code snippet we're printing out a string that we have properly wrapped in quotation marks. Please note that both single and double quotation marks work properly.
It's also important that you do not mix the quotation mark types. For example, if you attempted to run the code:
puts "Name an animal'
You would get an error, because you need to ensure that every quotation mark is matched with a closing (and matching) quotation mark.
If you start a string with double quotation marks, the Ruby parser requires that you end the string with the matching double quotation marks.
Lastly in this code snippet we're storing a string inside of a variable and then printing the value out to the console.
We'll talk more about strings and string interpolation in subsequent sections.
In this section, we are going to talk about string interpolation in Ruby.
So what exactly is string interpolation? Good question. String interpolation is the process of being able to seamlessly integrate dynamic values into a string.
Let's assume we want to slip dynamic words into a string. We can get input from the console and store that input into variables. From there we can call the variables inside of a pre-existing string.
For example, let's give a sentence the ability to change based on a user's input.
puts "Name an animal"
animal = gets.chomp
puts "Name a noun"
noun= gets.chomp
p "The quick brown #{animal} jumped over the lazy #{noun} "
Note the way I insert variables inside the string? They are enclosed in curly brackets and are preceded by a # sign.
If I run this code, this is what my output will look:
So, this is how you insert values dynamically in your sentences.
If you see sites like Twitter, it sometimes displays personalized messages such as: Good morning Jordan or Good evening Tiffany. This type of behavior is made possible by inserting a dynamic value in a fixed part of a string and leverages string interpolation.
Now, let's use single quotes instead of double quotes, to see what happens.
As you'll see, the string was printed as it is without inserting the values for animal and noun. This is exactly what happens when you try using single quotes—it prints the entire string as it is without any interpolation. Therefore it's important to remember the difference.
Another interesting aspect is that anything inside the curly brackets can be a Ruby script. So, technically you can type your entire algorithm inside these curly brackets, and Ruby will run it perfectly for you. However, it is not recommended for practical programming purposes.
For example, I can insert a math equation, and as you'll see it prints the value out.
In this section we are going to learn about string manipulation along with a number of examples of how to integrate string manipulation methods in a Ruby program.
So what exactly is string manipulation? It's the process of altering the format or value of a string, usually by leveraging string methods.
Let's start with an example. Let's say I want my application to always display the word Astros in capital letters. To do that, I simply write:
"Astros".upcase
Now if I always a string to be in lower case letters I can use the downcase method, like so:
"Astros".downcase
Those are both methods I use quite often. However there are other string methods available that we also have at our disposal.
For the rare times when you want to literally swap the case of the letters you can leverage the swapcase method:
"Astros".swapcase
And lastly if you want to reverse the order of the letters in the string we can call the reverse method:
"Astros".reverse
These methods are built into the String data class and we can call them on any string values in Ruby.
Another neat thing we can do is join different methods together to get custom output. For example, I can run:
"Astros".reverse.upcase
The preceding code displays the value SORTSA.
This practice of combining different methods with a dot is called method chaining.
In this section, we are going to walk through how to use the split and strip methods in Ruby. These methods will help us clean up strings and convert a string to an array so we can access each word as its own value.
Let's start off by analyzing the strip method. Imagine that the input you get from the user or from the database is poorly formatted and contains white space before and after the value. To clean the data up we can use the strip method. For example:
str = " The quick brown fox jumped over the quick dog "
p str.strip
When you run this code, the output is just the sentence without the white space before and after the words.
Now let's walk through the split method. The split method is a powerful tool that allows you to split a sentence into an array of words or characters. For example, when you type the following code:
str = "The quick brown fox jumped over the quick dog"
p str.split
You'll see that it converts the sentence into an array of words.
This method can be particularly useful for long paragraphs, especially when you want to know the number of words in the paragraph. Since the split method converts the string into an array, you can use all the array methods like size to see how many words were in the string.
We can leverage method chaining to find out how many words are in the string, like so:
str = "The quick brown fox jumped over the quick dog"
p str.split.size
This should return a value of 9, which is the number of words in the sentence.
To know the number of letters, we can pass an optional argument to the split method and use the format:
str = "The quick brown fox jumped over the quick dog"
p str.split(//).size
And if you want to see all of the individual letters, we can remove the size method call, like this:
p str.split(//)
And your output should look like this:
Notice, that it also included spaces as individual characters which may or may not be what you want a program to return.
This method can be quite handy while developing real-world applications. A good practical example of this method is Twitter. Since this social media site restricts users to 140 characters, this method is sure to be a part of the validation code that counts the number of characters in a Tweet.
We've walked through the split method, which allows you to convert a string into a collection of characters. Thankfully, Ruby also has a method that does the opposite, which is to allow you to convert an array of characters into a single string, and that method is called join. Let's imagine a situation where we're asked to reverse the words in a string. This is a common Ruby coding interview question, so it's an important concept to understand since it tests your knowledge of how string work in Ruby. Let's imagine that we have a string, such as:
str = "backwards am I"
And we're asked to reverse the words in the string. The pseudocode for the algorithm would be:
We can actually accomplish each of these requirements in a single line of Ruby code. The following code snippet will perform the task:
str.split.reverse.join(' ')
This code will convert the single string into an array of strings, for the example it will equal ["backwards", "am", "I"]. From there it will reverse the order of the array elements, so the array will equal: ["I", "am", "backwards"]. With the words reversed, now we simply need to merge the words into a single string, which is where the join method comes in. Running the join method will convert all of the words in the array into one string.
In this article, we were introduced to the string data type and how it can be utilized in Ruby. We analyzed how to pass strings into Ruby processes by leveraging string interpolation. We also learned the methods of basic string manipulation and how to find and replace string data. We analyzed how to break strings into smaller components, along with how to clean up string based data. We even introduced the Array class in this article.
Further resources on this subject: