class Set

An instance of class Set contains a collection of objects (elements), with no duplicates.

By default:

Calling compare_by_identity causes:

Set includes module Enumerable, and is easy to use with other enumerable objects. Many of its methods accept enumerable objects as arguments; any enumerable object may be converted to a set via to_set.

Contact

Inheriting from Set

Before Ruby 4.0 (released in December, 2025), class Set had a different, less efficient implementation. In Ruby 4.0, the class was reimplemented in C, and the behaviors of some methods were adjusted.

When compatibility with the older implementation is needed, a Set subclass should inherit directly from class Set; this automatically includes module Set::SubclassCompatible, which makes behaviors closer to those in the older implementation.

A difference may be seen as follows:

Set[[1, 2, 3]]       # => Set[[1, 2, 3]]
class MySet < Set; end
MySet[[1, 2, 3]]     # => #<MySet: {[1, 2, 3]}>  # Same as in Ruby 3.4.

When backward compatibility is not needed, a Set subclass should inherit from Set::CoreSet, which avoids including the compatibility layer:

class MyCoreSet < Set::CoreSet; end
MyCoreSet[[1, 2, 3]] # => MyCoreSet[[1, 2, 3]]

What’s Here

First, what’s elsewhere. Class Set:

In particular, class Set does not have many methods of its own for fetching or for iterating. Instead, it relies on those in Enumerable.

Here, class Set provides methods that are useful for:

Methods for Creating a Set

Methods for Set Operations

Methods for Comparing

Methods for Querying

Methods for Assigning

Methods for Deleting

Methods for Converting

Other Methods