Written by James BrittTechnically reviewed by Jim Freeze · Reviewed
Ruby Set 4.0 makes Set a core class, in place of the previous autoloaded standard-library implementation. Use sets when each value should appear once and membership matters more than position. The familiar operations remain: collect unique values, check membership and compare groups. When upgrading, also check inspection output and deprecated arguments to set-conversion methods.
Sets are good choices for collections of customer IDs that have been invited to a preview, tags associated with a document, names previously seen during an import. Arrays are generally better suited for ranked lists, sequences of events, or repeated measurements. Whether to choose a set or an Array ultimately depends on what a duplicate represents within your own application logic.

What changed in Ruby Set 4.0?
The most significant change related to Ruby sets is where sets live. In Ruby 3.4, Set lived in the standard library and was available through autoloading. Now that Ruby 4.0 offers it as a core class with a C implementation, you don’t need to load anything to create a set. However, older Ruby releases did provide autoloading, which means simply not having a loading statement isn’t necessarily enough to determine that you’re using a newer version.
In addition to providing a location for sets, Ruby’s official 4.0 release notes on GitHub mention two additional backwards compatibility considerations. First, inspection uses a simpler Set display. Second, passing arguments to the set-conversion methods on Set and Enumerable is deprecated. While neither of these changes necessitate rewriting every call to sets that existed prior to 4.0, find the specific calls and assertions impacted by the changes and address them specifically rather than doing mass editing across an entire project.
As an example, if a snapshot that validates the debug output of an object fails even though the members are valid, prefer a membership validation when membership is what constitutes the contract. If your application intends to expose the debug output format through logs or user interfaces, validate the new output format separately from the expected membership.
The overall Ruby 4.0 new features guide places this collection change alongside all of the other work involved in migrating to 4.0. Therefore, keep the migration focused: a new implementation is a reason to run your tests; it doesn’t mean every application will receive some particular speed improvement.
Build a set around a real question
Imagine you’re running a preview program and have invited customers 101, 102 and 103. You have another list that includes customers 102 and 104 who have completed the prerequisite. Both lists might contain duplicate values because they originated from separate exports. A set allows your code to express which customers belong to each group without treating duplicate rows as additional people.
This example demonstrates that the input of 102 twice results in only three unique members being stored in the invited set (101, 102 and 103). The membership check determines whether customer 102 was invited. It does not determine where that customer appears, how many times they were exported or which row arrived first. Those questions require information that the set discards intentionally.
invited = Set[101, 102, 102, 103]
ready = Set[102, 104]
p invited.size # 3
p invited.include?(102) # true
If you need to investigate duplicates more thoroughly, store the original raw data alongside the set of unique identifiers. Creating a set of unique values from an import can be helpful but it can also conceal a data quality issue. A practical import will typically maintain both the original raw data and a set of unique identifiers so there are clear purposes for each one.
The displayed examples passed 23 assertions in the official Ruby 4.0.0 WebAssembly runtime. That evidence covers the collection operations shown here. It does not establish native performance, memory usage or compatibility with every gem. Ruby 4.0.0 identifies the tested runtime; it is not a claim about the newest patch release.
Combine groups with Ruby Set 4.0
Union answers who exists in either group. For the preview example, that results in customers 101, 102, 103 and 104. Intersection answers who exists in both, leaving only 102. Difference answers who exists in the first group but not the second: invited customers who have not completed the prerequisite are 101 and 103.
p (invited | ready).to_a.sort # [101, 102, 103, 104]
p (invited & ready).to_a.sort # [102]
p (invited - ready).to_a.sort # [101, 103]
p (ready - invited).to_a.sort # [104]
Be careful of direction when comparing differences. If you reverse the order of the inputs and ask about customers who completed the prerequisite but were not invited, the answer would be 104. Naming the inputs and result makes the operation easier to review than a chain of operators using anonymous arrays.
Each expression returns a new set; therefore, the original invited group remains available for another comparison. For clarity, the examples sort their converted arrays only to provide stable output for printing. Sorting is part of presenting data; it does not impose a ranking on the underlying set.
To validate a subset question, verify that all members of a smaller group exist within the larger one. For example, the group containing only customer 102 is a subset of the invited group. This is useful when validating requested permissions against allowed permissions provided that you have already validated and normalized consistently any identifier used within your permission checks.
Equality and stable members
When creating a set using hashes and equality to identify duplicates, treat integer one and floating point one as distinct members. Similarly, a string containing “ruby” and a symbol named “ruby” remain distinct members. Do not assume values printed in similar formats collapse into single entries.
Normalization is a business decision. If two spellings should represent the same tag, normalize them before building your collection. However, avoid automatically changing case on identifiers whose case has significant meaning. Instead write a small test for your actual input rule rather than relying on your collection to guess it correctly.
Cornell’s hashing lesson describes why altering an object’s hash-relevant state after insertion can cause lookup failures. Although Cornell uses Java to illustrate this concept, the basic principle helps explain Ruby’s warning about mutable members in sets. Keep hash-relevant state stable while objects are stored in collections. If you create custom objects to serve as identities and must implement equality and hashing methods together, review them together rather than modifying only one method.
However, strings have a special case: sets store frozen copies of unfrozen strings. Thus even though you replace the original label “ruby” with “rails”, it does not impact the member stored in the set. This protection does not make every nested object immutable.
Update membership deliberately
Inserting an existing member does not increase the size of a set. That’s exactly what a visited items collection needs often enough. However, a workflow may also need to know if an insertion was new. The conditional-add method tells you whether the member was new. You do not have to infer this later from a size comparison.
The update example begins with customers 101 and 102. Adding 102 conditionally returns no new inserts; adding 103 succeeds. Removing 101 leaves only 102 and 103 inside the set.
members = Set[101, 102]
p members.add?(102) # nil
members.add?(103)
members.delete(101)
p members.to_a.sort # [102, 103]
These updates modify the set itself. By contrast, the earlier union and difference expressions returned separate results.
A helper that changes a shared collection can surprise its caller, especially when another step needs the original membership. Decide whether it updates the supplied set or returns a new result, then test that behaviour. A clear name helps. However, an assertion about the original collection gives stronger evidence.
Predict the output
Begin with customers 101 and 102, then add 102 again. Before revealing the answer, predict the number of members and the sorted output. Does the second insertion create another entry, replace the previous one or leave membership unchanged? This exercise checks the basic contract behind the longer preview example.
members = Set[101, 102]
members.add(102)
p members.size
p members.to_a.sort
Reveal the answer and explanation
2
[101, 102]
There are still two members. Adding 102 again leaves membership unchanged, so the sorted array contains 101 followed by 102. The example explicitly inspects the array to show brackets and separators. Printing individual members would create a different display without changing membership.
Upgrade checks for Ruby Set 4.0
First, search tests and snapshots for the old inspection format. Then look for conversions that pass arguments and review them against the deprecation. Retain the intended transformation when updating those calls; blindly removing arguments could change the members you construct.
Next, test the contracts your application relies on: duplicate handling, membership, group comparisons and whether helpers mutate their input. Include an empty collection and an absent value. If exports require a particular order, make that ordering explicit at the boundary and test it there.
Finally, benchmark only if your reason for changing code was related to performance. Use representative data, including construction time when the real application both creates the collection and queries it. A set built for one tiny lookup may not be a useful optimisation.
The examples here establish behaviour; they make no timing promises.
Before removing loading statements from a shared library, check its supported Ruby versions. A project that supports older interpreters needs tests on those interpreters too. The Ruby 4.0 checks in this guide cannot establish that an older runtime takes the same path. Also test custom Set subclasses if your application uses them; public membership behaviour matters more than private storage assumptions.
Takeaway
Use Ruby Set 4.0 to represent unique membership clearly. Choose an Array when order or repetitions belong to the data, and keep stable identifiers inside a Set.
Review display assertions and deprecated conversion arguments when upgrading projects. Then test the collection contracts your application needs, without assuming an unmeasured speed improvement.
