How to concatenate the arrays in Ruby
In this tutorial, we are going to learn about how to concatenate the arrays in Ruby with the help of examples.
Concatenation means the joining of two or more arrays into a single array.
Consider, we have the following two arrays:
prices = [3, 4, 5]
fruits = ["apple", "bananna", "grapes"]
Now, we need to join above two arrays like this:
[3, 4, 5, "apple", "bananna", "grapes"]
Using the plus ”+” operator
To concatenate the two arrays into a single array, we can use the plus operator +
in Ruby.
Here is an example:
prices = [3, 4, 5]
fruits = ["apple", "bananna", "grapes"]
result = prices + fruits
puts "#{result}"
Output:
[3, 4, 5, "apple", "bananna", "grapes"]
Using the concat() Method
Similarly, we can also use the built-in concat()
method in Ruby to concatenate array1 with array2.
The concat() method doesn’t modify the original array, instead of it returns the new array with the combination of array1 and array2.
Here is an example:
a = [1, 2, 3]
b = [4, 5, 6]
result = a.concat(b)
puts "#{result}"
Output:
[1, 2, 3, 4, 5, 6]
Similarly, we can also concatenate three arrays in the ruby like this:
a = [1, 2, 3]
b = [4, 5, 6]
c = [7, 8, 9]
result = a.concat(b, c)
puts "#{result}"
Output:
[1, 2, 3, 4, 5, 6, 7, 8, 9]