Strings are a sequence of alphanumeric and special symbols. They are a crucial building block in all programming languages.
Arrays, on the other hand, are a collection of ordered and indexed elements. Elements in an array can be of any object type, such as hash, integers, strings, symbols, and more.
As the name suggests, an array of strings is an array made up of string objects and no other type.
In this guide, we will learn how to work with arrays of strings and apply various methods such as join to combine the elements in the collection.
How to Create an Array of strings
If you want to create an array of strings, you can use various methods. The most apparent is the default array creation method, which is:
The above method will create an array of strings separated by commas.
Using Percent String
A better way to create an array of strings is to use the percent string notation. Below is an example:
The above syntax uses the percentage notation (%w) followed by the items to add to the array separated by whitespace.
Ruby will take all the elements and convert them to an array.
Instead of using a pair of curly braces, you can use other matching pairs such as:
- Parenthesis – %w()
- Square brackets – %w
- Angled brackets – %w<>
- Exclamation marks – %w!!
- Pound sign – %w##
- At symbol – %[email protected]@
If you have a string containing whitespace or a special character, you can use Ruby escape characters to ignore it.
How to Join an Array of Strings
You can join the elements in an array string using the join method. The method accepts two parameters: an array and a separator.
In the example above, we join the elements in the array and separate them with a semicolon.
The resulting value:
Let’s take an example array that contains valid SQL queries. Using the join method, you can create a combined query as:
"SELECT * FROM table_name",
"SELECT column FROM table",
"SELECT * FROM table WHERE name = 'James'",
combined_query = sql_queries.join(";")
The example above will separate the queries with a semicolon, rendering them a valid combined SQL query.
If you do not specify a delimiter for the join method, the method will return the characters for all the strings in the array.
combined_query = langs.join
The above example is similar to using the inject method as:
combined_query = langs.reduce(:+)
This guide discussed how to work with an array of strings and combine them to create a joined array of strings.