Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,406 questions

56,397 answers

573 users

How to find the intersection of two arrays (values that exist in both arrays) in Ruby

1 Answer

0 votes
# Frozen string literal pragma enables string allocation optimizations in Ruby.
# frozen_string_literal: true

# Finds the unique intersection of two arrays (values present in both).
#
# Ruby's Array#& / Array#intersection creates a unique set of common elements,
# maintaining the relative order of appearance from the first array.
#
# Time Complexity:  O(n + m) - Ruby uses an internal hash table under the hood.
# Space Complexity: O(n + m) - Allocates a new array for the resulting set.
#
# @param first [Array] The first array sequence.
# @param second [Array] The second array sequence.
# @return [Array] Array containing unique common elements.
def find_array_intersection(first, second)
  # Guard against nil inputs
  raise ArgumentError, 'Inputs must not be nil' if first.nil? || second.nil?

  # Array#& computes set intersection and automatically handles deduplication
  first & second
end

# --- Usage Example ---

arr1 = [5, 7, 1, 1, 3, 0, 6, 2]
arr2 = [2, 8, 8, 6, 9, 3, 3, 4, 4]

intersection = find_array_intersection(arr1, arr2)

puts "Arr1:         #{arr1.inspect}"
puts "Arr2:         #{arr2.inspect}"
puts "Intersection: #{intersection.inspect}"
# Output: Intersection: [3, 6, 2]



# run:
# 
# Arr1:         [5, 7, 1, 1, 3, 0, 6, 2]
# Arr2:         [2, 8, 8, 6, 9, 3, 3, 4, 4]
# Intersection: [3, 6, 2]
#

 



answered 6 days ago by avibootz
...