Limited Offer
60% OFF on all plans!

Set in Ruby

Work with the Set class for collections of unique values and set operations like union, intersection, and difference.

Set Basics

A Set in Ruby is an unordered collection of unique values. Unlike arrays, sets do not allow duplicates and are optimized for fast membership testing. Require `set` to use it (built-in since Ruby 3.2, but `require "set"` works in all versions).

1. Creating an Empty Set

Use `Set.new` to create an empty set.

2. Creating a Set with Initial Values

Pass an array to `Set.new` — duplicates are removed.

Basic Set Operations

Set provides methods to add, remove, and check values. All operations run in roughly O(1) time.

1. Adding Values

Use `add` or `<<` to insert values.

2. Membership Check

Use `include?` to check if a value exists.

3. Removing Values

Use `delete` to remove a value (no error if missing).

4. Size and Empty Check

Use `size` / `length` and `empty?`.

Mathematical Set Operations

Ruby Set supports all classic mathematical set operations using both operator syntax and method syntax.

1. Union (|)

Combine all unique elements from both sets.

2. Intersection (&)

Find common elements between two sets.

3. Difference (-)

Elements in the first set but not the second.

4. Symmetric Difference (^)

Elements in either set but not both.

Subset & Superset Checks

Ruby Set provides methods to check whether one set is contained within another.

1. Subset

`subset?` checks if all elements of one set exist in another.

2. Superset

`superset?` checks if a set contains all elements of another.

Traversal & Conversion

Since Set includes the Enumerable module, all collection methods like `each`, `map`, `select`, and `reject` work on sets.

1. Iterating with each

Use `each` to loop over all set elements.

2. Converting Set ↔ Array

Use `to_a` to get an array, and `Set.new(array)` to go back.