Concatenating an array is easy to do with the +
operator. When used with the two arrays, a new array is returned which is a concatenated array of both arrays.
array1 + array2
array1
: This is one of the arrays you want to concatenate with another array.
array2
: This is the second of the arrays you want to concatenate with another array.
The value returned is a new array that is the concatenation of the two arrays.
In the example below, we created some arrays and concatenated them using the +
operator. Run it and observe the output.
arr1 = [1, 2 ] arr2 = [3, 4, 5] arr3 = ["a", "b", "c"] arr4 = [ "d", "e"] arr5 = ["Ruby", "Java"] arr6 = [ "JavaScript", "Python"] arr7 = ["1ab", "2cd"] arr8 = ["3ef", "4gh", "5ij"] arr9 = [nil, "nil"] arr10 = ["true", "false", true] # concatenate arrays using the "+" operator a = arr1 + arr2 b = arr3 + arr4 c = arr5 + arr6 d = arr7 + arr8 e = arr9 + arr10 # print new arrays puts "#{a}" # returns [1, 2, 3, 4, 5] puts "#{b}" # returns ["a", "b", "c", "d", "e"] puts "#{c}" # returns ["Ruby", "Java", "JavaScript", "Python"] puts "#{d}" # returns ["1ab", "2cd", "3ef", "4gh", "5ij"] puts "#{e}" # returns [nil, "nil", "true", "false", true]
RELATED TAGS
CONTRIBUTOR
View all Courses