When working with arrays, you may encounter a scenario where you must join two or more arrays into a single array entity. This tutorial explores the various methods and techniques that we can use to join two or more arrays.
Create an Array in Ruby
In Ruby, we can create an array by enclosing a comma-separated list of values in square brackets [].
For example:
You can also have an array of string values as shown in the following:
Concatenate the Arrays in Ruby
We can use three main methods to concatenate the arrays in the Ruby programming language. These include:
- Using the Array#concat Method
- Using the Array#+ Method
- Using the Array#push Method
Let us explore each of these methods.
NOTE: It is good to remember that all the discussed methods always return a new array which contains the elements from the input arrays.
Concatenate the Arrays Using the Concat() Method
This most common and easiest method allows us to merge two arrays. The method takes the second array of the argument as shown in the following syntax:
The concat method is considered a destructive method. This means that the method modifies the original array.
An example is as follows:
words = ['one', 'two', 'three', 'four', 'five']
print(nums.concat(words))
This should return the output as follows:
The concat method appends the elements of the second array to the end of the first array.
Concatenate the Arrays Using the Array#+
We can also use the + operator to concatenate two arrays in Ruby. In this case, this operator adds the elements of the second array to the end of the first array.
In this case, the original arrays will not be modified. However, the method creates a new array and stores the values of the concatenation.
Example:
words = ['one', 'two', 'three', 'four', 'five']
print nums + words
Output:
Concatenate the Arrays Using the Array#push Method
As the method name suggests, we can use this method to push the elements of the second array to the end of the first element. Unlike the concat() method, this preserves the duplicate values from both arrays.
The syntax is as follows:
An example is as follows:
words = ['one', 'two', 'three', 'four', 'five']
print nums.push(words)
Output:
There you have it.
Conclusion
Using this tutorial, we learned how to use three Ruby methods – concat, push, and the + operator – to concatenate the Ruby arrays.