Ruby concat array method

In the Ruby programming language, the concat() array method is used to add an given arrays to existing array. Syntax of this method as follows.

concat(ar1, ...) → Reference of self array

More than one array can be added using this method, those is separate by comma. This method are returns the reference of apply array. Note some ruby version are allow concat() method with only single parameter.

Ruby concat method example

In this section mention, few examples of concat() method which are provide information to this method.

# Our array
arr1  = [1,2,3]
arr2  = [true,false]

# Display array
print("\n Array arr1 : ", arr1)
print("\n Array arr2 : ", arr2)

# concat single array
arr1.concat(["a","b"])

# concat two array
arr2.concat([1,2],[10.2,43])

# Display array
print("\n Array arr1 : ", arr1)
print("\n Array arr2 : ", arr2)
Ruby concat method example 1

 Array arr1 : [1, 2, 3]
 Array arr2 : [true, false]
 Array arr1 : [1, 2, 3, "a", "b"]
 Array arr2 : [true, false, 1, 2, 10.2, 43]

Important point, When concat(obj) parameter is an existing object which include array elements. Then this method are create new element of literasl and if object contain inner arrays then this is shared by both.

# Our array
arr1  = [10,20,30]
arr2  = [true,false,["a","b"], 40]

# Display array
print("\n Array arr1 : ", arr1)
print("\n Array arr2 : ", arr2)

# modified arr1
arr1.concat(arr2)

# Update arr2
arr2[0] = 'A';
arr2[2][0] = 'B';

# Display array
print("\n Array arr1 : ", arr1)
print("\n Array arr2 : ", arr2)
Ruby concat method example 2

 Array arr1 : [10, 20, 30]
 Array arr2 : [true, false, ["a", "b"], 40]
 Array arr1 : [10, 20, 30, true, false, ["B", "b"], 40]
 Array arr2 : ["A", false, ["B", "b"], 40]


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved