I have two arrays
a = [1, 2, 3, 4, 5] b = [2, 4, 6]
I would like to merge the two arrays, then remove the values that is the same with other array. The result should be:
c = [1, 3, 5, 6]
I've tried subtracting the two array and the result is [1, 3, 5]. I also want to get the values from second array which has not duplicate from the first array..
This can be done in a few ways in Ruby. The first is the plus operator. This will append one array to the end of another, creating a third array with the elements of both. Alternatively, use the concat method (the + operator and concat method are functionally equivalent).
concat() can be used to merge multiple arrays together. But, it does not remove duplicates.
Use Array#uniq
.
a = [1, 3, 5, 6] b = [2, 3, 4, 5] c = (a + b).uniq => [1, 3, 5, 6, 2, 4]
You can do the following!
# Merging c = a + b => [1, 2, 3, 4, 5, 2, 4, 6] # Removing the value of other array # (a & b) is getting the common element from these two arrays c - (a & b) => [1, 3, 5, 6]
Dmitri's comment is also same though I came up with my idea independently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With