DEV Community

Thieu Luu
Thieu Luu

Posted on

The .concat method

What is .concat method?
The .concat method is used to combine the elements of one array or string with another array or string. It's important to note that the original objects are modified in place.

Example:

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

# Using .concat to combine the elements of array1 and array2
array1.concat(array2)

puts array1 # Output: [1, 2, 3, 4, 5, 6]

string1 = "Hello, "
string2 = "world!"

# Using .concat to combine the strings
string1.concat(string2)

puts string1 # Output: Hello, world!
Enter fullscreen mode Exit fullscreen mode

*How and when to use .concat method? *
You would use the .concat method when you want to combine the elements of one array or string with another, and you prefer to modify the original object rather than creating a new one. This method is particularly useful when working with mutable objects like array and strings, where you want to update the existing data rather than creating a new object with the combined content.

Top comments (0)