How to use the minus(-) operator to compare two arrays in Ruby
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.
Syntax
array1 - array2
Parameters
array1: This is the first of the arrays you want to compare.
array2: This is the second of the arrays you want to compare.
Return value
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.
Code
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"]
Code explanation
In the code above, we created arrays that contain similar items.
- In line 2 and 3, we created arrays that contain integers.
- In line 5 and 6, we created arrays that contain alphabet characters.
- We compared these arrays with the
-operator. The returned values are arrays that have elements that are not present in two arrays that are compared. - Hence, we have
[6, 8, 10]printed in line 13, because these elements do not appear in botharr1andarr2. - In line 14,
["i", "o", "u"]were returned, because these elements are not present in botharr3andarr4.