How To Join Two Arrays In Ruby

Arrays are a fundamental data structure in most programming languages, including Ruby. They are ordered lists of elements, like numbers or strings, and can be manipulated to create a new array, add or remove elements, and more. In this tutorial, we will focus on how to join two arrays in Ruby using a couple of different methods.

Method 1: Using the + operator

The simplest way to join two arrays is by using the + operator. This operator concatenates two arrays and returns a new array containing the elements of both arrays, preserving their original order.

array1 = [1, 2, 3]
array2 = [4, 5, 6]

joined_array = array1 + array2
puts joined_array.inspect
# Output: [1, 2, 3, 4, 5, 6]

Method 2: Using the concat method

Another way to join two arrays is by using the concat method. This method takes the elements of the second array and appends them to the first array, modifying the first array in-place.

array1 = [1, 2, 3]
array2 = [4, 5, 6]

array1.concat(array2)
puts array1.inspect
# Output: [1, 2, 3, 4, 5, 6]

Note that the concat method modifies the original array. If you want to create a new array without modifying the original arrays, you can use the + operator or the Array#| method (described below).

Method 3: Using the Array#| method

If you want to join two arrays and remove duplicate elements, you can use the Array#| method. This method returns a new array containing the unique elements of both arrays, preserving their original order.

array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

unique_joined_array = array1 | array2
puts unique_joined_array.inspect
# Output: [1, 2, 3, 4, 5, 6]

In this example, the elements 3 and 4 are present in both arrays. The Array#| method removes the duplicates, resulting in a joined array with unique elements only.

Conclusion

In this tutorial, we discussed three methods to join two arrays in Ruby: using the + operator, the concat method, and the Array#| method. Each method has its own advantages and is suitable for different use cases. Choose the method that best fits your needs and start joining arrays like a pro!