Different arrays can have different elements depending on what kind of data stored in them. When you want to see elements that appear in one and do not appear in another, you compare them. You can use the -
operator on two arrays to get an array that removes items or elements that appear in the other. This way, we get a new array that does not contain elements present in both arrays.
array1 - array2
array1
: This is the first of the arrays you want to compare.
array2
: This is the second of the arrays you want to compare.
The value returned is a new array that is a copy of array1
, but removes items that also appear in array2
.
Note: The new array returned preserves the order of the elements from the first array or
array1
.
In the code example below, we create arrays that have similar kinds of data, and we compare them using the -
operator. Finally, we print the returned values to the console.
# create arraysarr1 = [2, 4, 6, 8, 10] # even numbersarr2 = [1, 2, 3, 4, 5] # ordinary numbersarr3 = ["a", "e", "i", "o", "u"] # vowelsarr4 = ["a", "b", "c", "d", "e"] # ordinary characters# compare arraysa = arr1 - arr2b = arr3 - arr4# print returned valuesputs "#{a}" # [6, 8, 10]puts "#{b}" # ["i", "o", "u"]
In the code above, we created arrays that contain similar items.
-
operator. The returned values are arrays that have elements that are not present in two arrays that are compared.[6, 8, 10]
printed in line 13, because these elements do not appear in both arr1
and arr2
.["i", "o", "u"]
were returned, because these elements are not present in both arr3
and arr4
.