What is array.concat() in Ruby?

When coding, there are times when you might want to join arrays to make them one. In this case, you can use the concat() method in Ruby. concat() is used to join, combine, concatenate, or append arrays. The concat() method returns a new array with all of the elements of the arrays combined into one.

Note: This method permanently changes the original array.

Syntax

array.concat(arr)

Parameters

  • arr: The array you wish to append to the original array, array.

Return Value

concat() returns a new array that has all of the elements of the arrays that were concatenated or appended.

Code example

In the example below, we create arrays and append other arrays to them. We then log the results to the console.

# creating arrays
array1 = [1, 2, 3, 4, 5]
array2 = ["a", "b", "c", "d", "e"]
array3 = ["Ruby on Rails!", "Java", "C++", "Python", "Javascript" ]
array4 = [nil, nil]
array5 = []
array6 = [false, true, 1, 0]
# append arrays
array1.concat([6, 7, 8])
array2.concat(["f", "g"])
array3.concat(["Golang"])
array4.concat(["nil"])
array5.concat(array6)
array6.concat(array1)
# print new arrays to the console
puts "#{array1}"
puts "#{array2}"
puts "#{array3}"
puts "#{array4}"
puts "#{array5}"
puts "#{array6}"

Free Resources