0
0
RubyHow-ToBeginner · 3 min read

How to Merge Two Arrays in Ruby: Simple Syntax and Examples

In Ruby, you can merge two arrays using the + operator or the concat method. The + operator returns a new array combining both arrays, while concat modifies the original array by adding elements from the second array.
📐

Syntax

There are two common ways to merge arrays in Ruby:

  • array1 + array2: Returns a new array with elements from both arrays.
  • array1.concat(array2): Adds elements of array2 to array1 modifying it.
ruby
merged_array = array1 + array2
array1.concat(array2)
💻

Example

This example shows how to merge two arrays using both the + operator and the concat method.

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

# Using + operator
merged = array1 + array2
puts "Merged with +: #{merged.inspect}"

# Using concat method
array1.concat(array2)
puts "Array1 after concat: #{array1.inspect}"
Output
Merged with +: [1, 2, 3, 4, 5, 6] Array1 after concat: [1, 2, 3, 4, 5, 6]
⚠️

Common Pitfalls

A common mistake is expecting + to modify the original array. It does not; it returns a new array instead. Also, using concat changes the original array, which might be unexpected if you want to keep it unchanged.

ruby
array1 = [1, 2]
array2 = [3, 4]

# Wrong: expecting array1 to change
array1 + array2
puts array1.inspect  # Output: [1, 2]

# Right: use concat to modify array1
array1.concat(array2)
puts array1.inspect  # Output: [1, 2, 3, 4]
Output
[1, 2] [1, 2, 3, 4]
📊

Quick Reference

Summary of methods to merge arrays in Ruby:

MethodDescriptionModifies Original?
array1 + array2Returns a new merged arrayNo
array1.concat(array2)Adds elements of array2 to array1Yes
array1.push(*array2)Adds elements of array2 to array1Yes

Key Takeaways

Use + to merge arrays without changing originals.
Use concat to add elements to an existing array.
Remember + returns a new array; it does not modify.
Be careful with concat as it changes the original array.
You can also use push(*array2) to merge arrays in place.