ruby merge arrays unique
To merge arrays and remove duplicates in Ruby, you can use the |
operator or the uniq
method. Here are the steps to achieve this:
- Define two arrays, let's call them
array1
andarray2
, which contain the elements you want to merge. - Use the
|
operator to merge the arrays. This operator performs a set union operation, which means it combines the arrays and removes any duplicates. Assign the result to a new array, let's call itmerged_array
.
Example:
array1 = [1, 2, 3]
array2 = [3, 4, 5]
merged_array = array1 | array2
In this example, merged_array
will be [1, 2, 3, 4, 5]
.
Alternatively, you can use the uniq
method to achieve the same result:
array1 = [1, 2, 3]
array2 = [3, 4, 5]
merged_array = array1.concat(array2).uniq
In this example, merged_array
will also be [1, 2, 3, 4, 5]
.
Both the |
operator and the uniq
method ensure that no duplicate elements are present in the merged array.