Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

ruby
array
communitycreator

How to use the minus(-) operator to compare two arrays in Ruby

okwudili onyejiaku

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 arrays
arr1 = [2, 4, 6, 8, 10]   # even numbers
arr2 = [1, 2, 3, 4, 5]    # ordinary numbers

arr3 = ["a", "e", "i", "o", "u"]   # vowels
arr4 = ["a", "b", "c", "d", "e"]   # ordinary characters 

# compare arrays
a = arr1 - arr2
b = arr3 - arr4

# print returned values
puts "#{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 both arr1 and arr2.
  • In line 14, ["i", "o", "u"] were returned, because these elements are not present in both arr3 and arr4.

RELATED TAGS

ruby
array
communitycreator
RELATED COURSES

View all Courses

Keep Exploring