/ Tags: RUBY-CODE / Categories: SOLUTIONS

Find Intersection Of Arrays Or Sets Cleanly In Ruby 3

Ruby 3+ provides elegant ways to find common elements between arrays, sets, or enum collections using intersection (&) or Set#intersection. This is especially useful for filtering, authorization checks, tag matching, or data deduplication.

Description

When comparing two or more collections in Ruby, you often want to know what values they share. Ruby’s built-in Array#& method finds intersection values while removing duplicates. For larger datasets or when working with non-array types (like enums or tag lists), the Set class offers better performance and readability using Set#intersection or Set#&.This approach is highly readable, concise, and great for permission checks, shared values, or filtering related records.

Sample input:

  user_tags = ["ruby", "rails", "api"]
  required_tags = ["graphql", "api", "rails"]


Sample Output:

   ["rails", "api"]

Answer

    # Simple array intersection
    common = user_tags & required_tags
    # => ["rails", "api"]

    # Using Set for performance with large or unsorted data
    require 'set'

    user_set = Set.new(user_tags)
    required_set = Set.new(required_tags)

    common = user_set & required_set
    or: user_set.intersection(required_set)
    # => #<Set: {"rails", "api"}>

Learn More

cdrrazan

Rajan Bhattarai

Software Engineer by work! 💻 🏡 Grad. Student, MCS. 🎓 Class of '23. GitKraken Ambassador 🇳🇵 2021/22. Works with Ruby / Rails. Photography when no coding. Also tweets a lot at TW / @cdrrazan!

Read More