0
0
RubyHow-ToBeginner · 3 min read

How to Find Difference of Arrays in Ruby Easily

In Ruby, you can find the difference between two arrays using the - operator, which returns a new array with elements from the first array that are not in the second. For example, [1, 2, 3] - [2] results in [1, 3].
📐

Syntax

The difference between two arrays is found using the - operator.

  • array1 - array2: Returns a new array with elements from array1 that are not in array2.
ruby
result = array1 - array2
💻

Example

This example shows how to find elements in the first array that are not in the second array.

ruby
array1 = [1, 2, 3, 4, 5]
array2 = [2, 4]
difference = array1 - array2
puts difference.inspect
Output
[1, 3, 5]
⚠️

Common Pitfalls

One common mistake is expecting the difference operation to be symmetric. The - operator is not symmetric; array1 - array2 is different from array2 - array1.

Also, the difference removes all occurrences of elements found in the second array.

ruby
a = [1, 2, 3]
b = [2, 3, 4]

# Wrong assumption: symmetric difference
puts (a - b).inspect  # Outputs [1]
puts (b - a).inspect  # Outputs [4]

# To get symmetric difference, combine both differences and remove duplicates
symmetric_diff = (a - b) + (b - a)
symmetric_diff.uniq!
puts symmetric_diff.inspect  # Outputs [1, 4]
Output
[1] [4] [1, 4]
📊

Quick Reference

Summary tips for finding array differences in Ruby:

  • Use - to get elements in the first array not in the second.
  • Difference is not symmetric; order matters.
  • To get symmetric difference, combine both - operations and remove duplicates.

Key Takeaways

Use the - operator to find elements in one array not present in another.
The difference operation is not symmetric; order of arrays matters.
To get symmetric difference, combine both array1 - array2 and array2 - array1 and remove duplicates.
The - operator removes all occurrences of matching elements from the first array.
Always use inspect or p to clearly see array outputs in Ruby.