0
0
Rubyprogramming~5 mins

Array comparison and set operations in Ruby

Choose your learning style9 modes available
Introduction

We use array comparison and set operations to find common, different, or combined items between lists. This helps us organize and compare data easily.

You want to find which friends you have in common with someone else.
You need to see what items are missing from your shopping list compared to a recipe.
You want to combine two lists of tasks without repeating any.
You want to check if two lists have exactly the same items.
You want to remove duplicates from a list.
Syntax
Ruby
array1 & array2   # Intersection: items common to both arrays
array1 | array2   # Union: all unique items from both arrays
array1 - array2   # Difference: items in array1 not in array2
array1 == array2  # Equality: checks if arrays have same items in same order
array1.eql?(array2) # Strict equality including type and order

The & operator finds items present in both arrays.

The | operator combines arrays but removes duplicates.

Examples
Intersection finds common items 2 and 3.
Ruby
a = [1, 2, 3]
b = [2, 3, 4]
puts a & b  # Output: [2, 3]
Union combines all unique items from both arrays.
Ruby
a = [1, 2, 3]
b = [3, 4, 5]
puts a | b  # Output: [1, 2, 3, 4, 5]
Difference shows items in a not in b.
Ruby
a = [1, 2, 3]
b = [2, 3]
puts a - b  # Output: [1]
Equality checks if arrays have same items in same order.
Ruby
a = [1, 2, 3]
b = [1, 2, 3]
puts a == b  # Output: true
Sample Program

This program shows how to compare two arrays using intersection, union, difference, and equality.

Ruby
array1 = [1, 2, 3, 4]
array2 = [3, 4, 5, 6]

puts "Array 1: #{array1}"
puts "Array 2: #{array2}"

intersection = array1 & array2
union = array1 | array2
difference = array1 - array2
are_equal = array1 == array2

puts "\nIntersection (common items): #{intersection}"
puts "Union (all unique items): #{union}"
puts "Difference (items in array1 not in array2): #{difference}"
puts "Are arrays equal? #{are_equal}"
OutputSuccess
Important Notes

Time complexity for these operations depends on array size, usually O(n*m) for intersection and difference.

Space complexity is O(n + m) because new arrays are created for results.

Common mistake: Using == checks order and content, not just content. Use set operations for content comparison.

Use intersection when you want common items, difference to find missing items, and union to combine without duplicates.

Summary

Array comparison helps find common, different, or combined items between lists.

Use & for intersection, | for union, and - for difference.

Equality == checks if arrays have the same items in the same order.