Ruby - Merge Two Arrays

1. Introduction

Merging two arrays is a common operation in programming, allowing us to combine elements from both sources into a single new array. In Ruby, there are multiple ways to merge arrays, but this post will guide you through one of the simplest methods.

2. Program Steps

1. Define two arrays.

2. Use the + operator to merge them.

3. Print the merged array.

3. Code Program

# Define two arrays
arr1 = [1, 2, 3]
arr2 = [4, 5, 6]
# Merge the arrays using `+` operator
merged_array = arr1 + arr2
# Print the merged array
puts "Merged array: #{merged_array}"

Output:

Merged array: [1, 2, 3, 4, 5, 6]

Explanation:

1. arr1 = [1, 2, 3] and arr2 = [4, 5, 6]: Here, we define two arrays named arr1 and arr2.

2. merged_array = arr1 + arr2: The + operator is used to concatenate the two arrays together, effectively merging them.

3. puts "Merged array: #{merged_array}": We display the result of the merged arrays.

Using the + operator provides an easy and intuitive way to merge arrays in Ruby. Note that this method creates a new array without modifying the original arrays.


Comments