In Ruby, the Set class is a collection of unordered, unique values—kind of like an array, but with no duplicates allowed. It maintains unique elements only. Supports set operations: union, intersection, difference, etc.

How to use:

require "set"

s = Set.new([1, 2, 3])
s.add(3)      # duplicate, won't be added
s.add(4)
puts s.inspect  # => #

Set Operations:

a = Set.new([1, 2, 3])
b = Set.new([3, 4, 5])

puts a | b     # Union => #
puts a & b     # Intersection => #
puts a - b     # Difference => #

Conversion:

arr = [1, 2, 2, 3]
unique_set = Set.new(arr)
puts unique_set.to_a  # => [1, 2, 3]

When to Use Set:

  • When you need to automatically eliminate duplicates.
  • When performing set-theoretic operations (like unions or intersections).
  • For efficient membership checks (similar to using a hash).