Ruby / Contracts: callables, evaluation, failures, and value models / Lesson 14
Sets and stable membership
Model unique Ruby Set members and protect stable hash keys.
On this page
Lesson goals
- Choose a set when uniqueness is required.
- Test membership without assuming order.
- Choose set algebra and representation according to uniqueness and ordering requirements.
- Design stable membership and snapshot ownership for mutable values.
Define uniqueness
A set represents unique members and supports operations such as membership, union, and intersection. Ruby’s Set is available from the standard library and requires loading it. Choose a set when uniqueness is part of the contract, not simply to remove duplicates without considering their meaning. State whether input normalization occurs before insertion and whether callers depend on any ordering.
Insert and check members
The example inserts repeated labels and checks the resulting size and membership. A duplicate does not add another member. This models a set of labels, not a frequency table; use a hash of counts when occurrences matter. Normalize only according to a documented rule, since case folding or trimming can merge values the domain considers distinct.
require "set"
labels = Set.new(["red", "blue", "red"])
puts labels.size
puts labels.include?("red")
2
true
The repeated red label is stored once.
Combine sets
Union contains members from either set, while intersection contains members present in both. The second example checks a shared label without relying on printed set order. Decide whether an operation should create a new set or mutate an existing one, and read the method’s contract. Avoid exposing an internal mutable set when a caller should receive an independent snapshot.
require "set"
a = Set.new(["red", "blue"])
b = Set.new(["blue", "green"])
puts (a & b).include?("blue")
true
Blue belongs to both sets.
Keep keys stable
Set membership depends on hashing and equality behavior of its elements. Mutating an object in a way that changes its hash or equality while it is stored can make lookup unreliable. Prefer stable keys and document ownership of mutable members. A new outer set does not necessarily deep-copy nested objects, so independence must be checked at each mutable boundary.
Test set behavior
Test empty input, duplicates, a missing member, and equal values created independently. Assert membership or compare sets rather than depending on an incidental printed order. If normalization is required, add cases that differ only by the documented normalization rule. Test that a caller cannot mutate internal state when the API promises a snapshot.
Define uniqueness and input meaning
Ruby Set is supplied by the standard library and is loaded with require 'set'. A set represents membership of unique elements under its equality and hashing rules. Inserting the same value again does not record another occurrence. That is useful for a collection of distinct tags or identifiers, but it loses information if a report needs counts or original order. A frequency hash or an array may be the better model when repetition or sequence is part of the requirement; choose from the domain meaning before converting the data.
Normalization must also be a deliberate boundary. Trimming or case-folding labels before insertion can merge values that the original system considers distinct. Define which transformations are allowed and whether the original representation must be retained, then test a pair that differs only by the normalization. Do not assume that a deduplicated set proves every input was valid or authorized. Record invalid inputs and any lost occurrence information separately when the application needs an audit trail.
Choose set operations by the question
Union contains elements present in either input; intersection contains those present in both; difference contains elements of the first input that are absent from the second. Direction matters for difference. A subset check asks whether every element of one set is contained in another, while disjointness asks whether there is no common element. Write the question in domain terms before selecting an operator: eligible users not yet assigned is a different set from assigned users who are no longer eligible.
Read each method’s mutation contract. Set operators such as union, intersection and difference return new sets, while operations such as add and delete modify the receiver. A new outer set does not automatically make nested mutable elements independent. Avoid asserting incidental iteration or inspection order in correctness tests; compare sets or check membership. If an ordered report is required, derive and sort an appropriate list explicitly under the application’s ordering policy.
Keep membership semantics stable
Set uses hash-based membership; its elements need consistent hash and eql? behavior for the intended equivalence. Equal independent value objects should be tested as members, not assumed distinct merely because they have different identities. A collision in hash values does not itself make unequal objects equal. Custom member classes need matching equality and hash definitions over the same stable fields, and tests should verify membership with an equal independent instance and rejection of a different one.
Changing fields that affect hash or eql? while an object is in a set can damage membership lookup because the internal index reflects earlier state. Prefer immutable member values or privately owned stable copies, and remove and reinsert under a deliberate update policy if an element must change. Ruby Set documents special handling for unfrozen String elements, but that does not recursively protect arrays or arbitrary nested objects. Do not generalize a particular String case into a deep immutability guarantee.
Make snapshots and mutation explicit
A method that exposes its internal mutable Set can let callers add or delete elements without passing through validation. Decide whether the reader returns a live shared set, a separate outer set or a deeper immutable snapshot. A shallow copy can isolate add and delete on the outer container while still sharing mutable element objects. Copy and freeze only the levels required by the documented data shape, and avoid freezing caller-owned objects as an accidental side effect.
Set algebra and membership are local collection operations, not a complete authorization policy or database transaction. A successful membership check proves membership according to the tested set’s current state, not that an identity is authenticated or that permission remains current in another service. If a set is shared across threads or persisted across requests, establish synchronization, durability and refresh policies at those actual boundaries. A synthetic in-memory example cannot establish those guarantees.
Verify membership without accidental ordering
Build a matrix covering empty input, duplicate input, present and missing elements, equal independent values and unequal values. For algebra, test members unique to each side as well as a shared member, and verify that non-mutating operators leave the inputs unchanged. When normalization is part of the contract, include examples that should merge and examples that must remain distinct. Check results by set equality or membership; assert a sorted list only if sorting is a documented presentation step.
Test ownership by attempting outer and nested mutation through any returned snapshot, and test stable-key lookup after the caller changes its original input. No examples here connect to a service or production data. Ruby was unavailable in the authoring environment, so the source and expected results are reasoned from Ruby 3.3 documentation rather than observed runs. Run the examples in an isolated compatible interpreter before claiming runtime evidence, and test concurrent or persistent behavior separately.
20 worked examples
1. Empty membership
Problem: Check size and membership of an empty set.
- No elements were inserted into the new set.
- Its size is zero and it does not contain the queried value.
require 'set'
s = Set.new
p s.size
p s.include?('A')
0
false
Why this result follows: An empty set has no member to match.
2. Set versus occurrence counts
Problem: Compare unique categories with a frequency count.
- The input contains A twice and B once.
- The set has two members while the frequency for A is two.
require 'set'
values = ['A', 'A', 'B']
puts Set.new(values).size
puts values.count('A')
2
2
Why this result follows: Uniqueness and occurrence frequency answer different questions.
3. Missing member
Problem: Check a value absent from a finite set.
- The set contains A and B.
- C is not one of those members.
require 'set'
s = Set['A', 'B']
p s.include?('C')
false
Why this result follows: Membership reports absence without relying on display order.
4. Union covers both inputs
Problem: Check members contributed by either input.
- The first set supplies A and B; the second supplies B and C.
- Their union includes both A and C.
require 'set'
a = Set['A', 'B']
b = Set['B', 'C']
u = a | b
p u.include?('A')
p u.include?('C')
puts u.size
true
true
3
Why this result follows: Union keeps each distinct member from either side.
5. Directional difference
Problem: Compare the two directions of set difference.
- A belongs only to the first set and C only to the second.
- Reversing the operands reverses which unique member remains.
require 'set'
a = Set['A', 'B']
b = Set['B', 'C']
p((a - b).include?('A'))
p((b - a).include?('C'))
true
true
Difference depends on operand order.
Why this result follows: Difference depends on operand order. A belongs only to the first set and C only to the second.
6. Subset relationship
Problem: Check whether all requested permissions are available.
- The requested set contains read only.
- The available set contains both read and write.
require 'set'
requested = Set[:read]
available = Set[:read, :write]
p requested.subset?(available)
true
Why this result follows: Every requested element is present in the available set.
7. Disjoint inputs
Problem: Check whether two categories share any member.
- The first set contains 1 and 2.
- The second contains 3 and 4, with no overlap.
require 'set'
p Set[1, 2].disjoint?(Set[3, 4])
true
Why this result follows: Disjointness reports that the intersection is empty.
8. Non-mutating union
Problem: Verify union leaves the original set unchanged.
- The union produces a new set containing A and B.
- The first input still contains only A.
require 'set'
a = Set['A']
u = a | Set['B']
p u.include?('B')
p a.include?('B')
true
false
Why this result follows: The operator creates a new outer set in this fixture.
9. Add mutates the receiver
Problem: Observe an explicit insertion. The set starts with A only.
- The set starts with A only.
- add inserts B into the same receiver.
require 'set'
s = Set['A']
s.add('B')
p s.include?('B')
true
Why this result follows: The mutating operation changes the receiver.
10. Delete a member
Problem: Remove a value and check the result.
- B is initially a member.
- delete removes B from the receiver while leaving the other member A.
require 'set'
s = Set['A', 'B']
s.delete('B')
p s.include?('B')
p s.include?('A')
false
true
Why this result follows: Removing B leaves the unrelated member A.
11. Equal independent members
Problem: Check membership with a separate equal array.
- The inserted array and queried array contain the same element.
- Their value equality and hashing allow the membership check to succeed.
require 'set'
a = [1]
s = Set[a]
p s.include?([1])
p a.equal?([1])
true
false
Why this result follows: Membership is not simply outer object identity.
12. Symbol and string members
Problem: Compare membership of a symbol and a similar-looking string.
- The set contains the symbol :id.
- The distinct String id is not the same member.
require 'set'
s = Set[:id]
p s.include?('id')
p s.include?(:id)
false
true
Why this result follows: Member type is part of the equality contract in this fixture.
13. Case-sensitive labels
Problem: Keep two differently cased strings distinct.
- The set is built without normalization.
- The strings red and Red are distinct values.
require 'set'
s = Set['red', 'Red']
puts s.size
2
Why this result follows: A set does not infer a case-folding policy.
14. Normalize before insertion
Problem: Apply a declared lowercase policy to two labels.
- Both source labels are converted to lowercase.
- The resulting equal strings occupy one set membership.
require 'set'
labels = ['red', 'Red']
s = Set.new(labels.map(&:downcase))
puts s.size
1
Why this result follows: The application’s explicit normalization determines the equivalence.
15. Shallow outer copy
Problem: Change a copied set without adding to the original.
- dup creates a different outer set.
- Adding B to the copy does not add it to the original.
require 'set'
a = Set['A']
b = a.dup
b.add('B')
p a.include?('B')
p b.include?('B')
false
true
Why this result follows: Outer container mutation is isolated by this copy.
16. Nested reference remains shared
Problem: Observe an array member after a shallow set copy.
- The duplicate set contains the same array object.
- Both outer sets still reference that mutable member.
require 'set'
item = [1]
a = Set[item]
b = a.dup
p a.first.equal?(b.first)
true
Why this result follows: A separate outer set is not a deep copy of its elements.
17. String key copy on insertion
Problem: Change the original string after inserting it into a set.
- Set protects an unfrozen String element by storing a frozen copy.
- Changing the caller’s original does not turn the stored A into AB.
require 'set'
text = String.new('A')
s = Set[text]
text << 'B'
p s.include?('A')
p s.include?('AB')
true
false
Why this result follows: This documented String behavior does not apply to arbitrary nested mutable objects.
18. Stable custom value
Problem: Look up an independent value using consistent equality and hash.
- Both keys use the same stable integer identifier.
- eql? and hash derive from that identifier, so membership succeeds.
require 'set'
class Key
def initialize(id); @id = id; end
attr_reader :id
def eql?(other); other.instance_of?(Key) && id.eql?(other.id); end
def hash; [self.class, id].hash; end
end
s = Set[Key.new(1)]
p s.include?(Key.new(1))
true
Why this result follows: Compatible equality and hashing support the independent lookup.
19. Hash collision without equality
Problem: Distinguish equal hash values from equivalent members.
- The two objects deliberately return the same hash number.
- Their identity-based eql? regards them as different members.
require 'set'
class Key
def hash; 1; end
def eql?(other); equal?(other); end
end
a = Key.new
b = Key.new
s = Set[a]
p s.include?(b)
false
Why this result follows: A collision alone does not establish membership equivalence.
20. Sorted presentation
Problem: Produce an explicit ordered display from a set.
- The set contains the two distinct labels.
- Converting to an array and sorting defines the display order.
require 'set'
s = Set['B', 'A']
puts s.to_a.sort.join(',')
A,B
Why this result follows: The order comes from the explicit sort, not an assumed set display.
Common errors and fixes
A duplicate disappears unexpectedly
- Why it happens
- A set stores unique members.
- How to fix it
- Use counts when occurrences matter.
- Prevent it next time
- State the collection contract.
A stored member cannot be found
- Why it happens
- Its hash or equality changed after insertion.
- How to fix it
- Use stable keys and rebuild affected state.
- Prevent it next time
- Avoid mutating hash-relevant fields.
A test fails due to output order
- Why it happens
- It relied on incidental set display order.
- How to fix it
- Assert membership or compare sets.
- Prevent it next time
- Document any ordering requirement.
20 practice exercises
1. How many members are in Set.new(["red", "red"])?
Show hint
Count unique values rather than array positions.
Show worked solution
One. The repeated value does not add a second member.
Both input strings represent the same set member under the stated equality behavior, so the resulting size is one. Check membership separately if the question also asks which label remains.
Check your solution
- The set size is one.
- The set contains red.
2. When is a frequency hash preferable to a set?
Show hint
Ask whether repeated occurrences carry meaning.
Show worked solution
Use counts when the number of occurrences matters; a set records only membership.
A set records whether a member is present, not how many times it occurred. Use a frequency hash when the report needs counts, and define normalization before deciding which inputs contribute to the same key.
Check your solution
- The explanation identifies lost occurrence counts.
- The proposed count policy states how equivalent inputs are grouped.
3. A report receives A, A, B, A and needs both distinct labels and occurrence counts. Choose structures and give the result.
Show hint
Uniqueness and frequency are different outputs.
Show worked solution
Use a set for the distinct labels A and B and a frequency hash for A:3 and B:1. Preserve the original sequence separately if order also matters; a set cannot reconstruct the three A occurrences.
Check your solution
- The distinct set contains A and B.
- The counts are A:3 and B:1.
4. Eligible users are A, B, C and assigned users are B, D. Build a three-way report: retain, add and investigate removal, with a separate confirmation before any change.
Show hint
Intersection and the two directional differences have different meanings.
Show worked solution
The intersection {B} is retained, eligible minus assigned {A, C} are candidates to add, and assigned minus eligible {D} are candidates to investigate. Confirm source freshness and authorization before acting; the set calculation itself makes no change.
Check your solution
- The report identifies B to retain and A, C as add candidates.
- D is only an investigation candidate until the separate confirmation.
5. A request requires read and write, while the available set contains read and audit. Design a subset check and identify the missing permission.
Show hint
The requested set must be contained in the available set.
Show worked solution
requested.subset?(available) is false because write is missing. Compute requested - available to identify {write}; evaluate real authorization separately rather than assuming this local fixture grants access.
Check your solution
- The subset check is false.
- The missing set contains write.
6. Two sources must have no shared IDs before merging. Source one has 1 and 2; source two has 2 and 3. Specify a check and a conflict report.
Show hint
Disjointness and intersection answer related but distinct questions.
Show worked solution
disjoint? is false because 2 appears in both. Compute the intersection to report {2}, then reject or resolve the conflict according to policy; do not silently deduplicate if duplicate origin matters.
Check your solution
- The sources are not disjoint.
- The reported conflict is ID 2.
7. A set operation must combine two inputs without modifying either. Design tests for result membership and both original sets.
Show hint
Choose a non-mutating operator and observe all three sets.
Show worked solution
Use union to create the combined set, then verify its expected members and compare each input to a saved expected set. Add a member to the result and check that the original outer sets still have their previous membership.
Check your solution
- The union contains all expected distinct members.
- Neither input’s outer membership changes.
8. A product considers labels case-insensitive but requires an audit of their original spelling. Design a normalization and reporting approach.
Show hint
A set of normalized values alone loses original representation.
Show worked solution
Normalize according to the documented case policy before building the membership set, while retaining the original labels and their source associations separately. Test labels that merge under the rule and a pair that remains distinct.
Check your solution
- Equivalent spellings map to one membership under the policy.
- Original spellings remain available for the audit.
9. An API returns its internal Set directly despite promising callers cannot change membership. Design a test and a safer return policy.
Show hint
A live mutable container exposes insertion and deletion.
Show worked solution
Return an independent outer copy or an immutable snapshot according to the API contract. Add and delete through the returned value and verify internal membership is unchanged; if elements are mutable, test their ownership separately.
Check your solution
- Caller changes do not alter internal membership.
- Nested mutable-element policy is explicitly checked.
10. Two independent custom values have equal stable ids. Compare membership and size in an ordinary Set and an identity-comparison Set after inserting both.
Show hint
The equality mode changes whether distinct instances collapse.
Show worked solution
With consistent value eql? and hash, the ordinary set has one member and recognizes either value. In identity mode the two distinct objects remain separate members, giving size two; test both sizes and document which policy the application needs.
Check your solution
- The ordinary value set has one member.
- The identity-comparison set has two members.
11. A mutable key object is edited after insertion into a set. Explain the membership risk and design a stable update workflow.
Show hint
The stored index may reflect the previous hash.
Show worked solution
Avoid changing equality-defining fields while stored. Remove the old member before changing or construct a new stable value, then insert it under the documented policy; test membership before and after and inspect possible conflicts.
Check your solution
- The update does not mutate an active member’s equality fields.
- Membership and conflicts are verified after reinsertion.
12. A shallow set copy contains a mutable array member. Design a test showing why outer independence does not imply member independence.
Show hint
Inspect member identity as well as container identity.
Show worked solution
Duplicate the set, verify the outer sets are distinct, then compare their corresponding array member identities. In an isolated fixture observe a mutation through both references, but do not rely on membership lookup after changing a hash-relevant member.
Check your solution
- The outer containers have different identities.
- The nested member is shown to be shared.
13. A copied Set contains two mutable arrays; one contains a mutable string. Design a test that distinguishes outer-set independence, shared arrays and shared nested strings.
Show hint
Each mutable level needs its own observation.
Show worked solution
Duplicate the set and assert distinct outer identities, then retain references to the original and copied corresponding arrays and string. Compare their identities and mutate the string in an isolated fixture; inspect both references without relying on membership lookup after the key changes.
Check your solution
- The copied set has a separate outer identity.
- The test exposes sharing at both array and string levels.
14. Compare inserting an unfrozen String and an Array into an ordinary Set, then editing the original objects. Design observations without relying on lookup after the array key changes.
Show hint
String insertion has documented special handling; an array member can remain shared.
Show worked solution
Retain references to the stored values before editing. Verify the set retains the original String value after the caller edits its source, while the stored array reference is the same object as the caller’s array; do not use membership lookup to infer behavior after mutating that array.
Check your solution
- Editing the source String does not change the stored String member.
- The array identity is shared and its mutation is not used to assert reliable membership.
15. A report compares Set inspection strings to test correctness and fails when order changes. Design an order-independent test and an ordered display contract.
Show hint
Membership and presentation are different requirements.
Show worked solution
Compare the result with an expected Set or assert required and absent members. If display order is required, convert to a list and sort under the declared ordering policy, then test that presentation separately.
Check your solution
- Correctness does not depend on inspection order.
- The display is sorted only under an explicit policy.
16. A set holds IDs from two sources, but duplicate IDs may signal an import error. Design validation before union.
Show hint
Union removes duplicate membership and can hide a conflict.
Show worked solution
Compute the intersection of the two source sets before union, report or reject overlapping IDs according to policy, and retain source provenance. Only combine after the conflict decision; test one overlap and one disjoint pair.
Check your solution
- An overlapping ID is reported before combination.
- A disjoint pair can proceed under the stated policy.
17. A custom set member compares only id in eql? but hashes id and mutable status. Explain the broken contract and repair it.
Show hint
Equal objects must have compatible hash values.
Show worked solution
If status differs while ids match, eql? can return true but differing status-based hashes may not agree. Derive both methods from the same stable equivalence fields, or include status in both if that matches the domain; test independent equal values.
Check your solution
- Equal members produce compatible hashes.
- The chosen equality fields remain stable while stored.
18. A membership set is cached across requests and can become stale. Define freshness and verification separately from set correctness.
Show hint
A correct in-memory set can still be out of date.
Show worked solution
Document the source, refresh interval or invalidation trigger and ownership of the cached set. Test membership after an authorized source change and refresh, and perform the real permission check at the authoritative boundary.
Check your solution
- A source change is reflected after the documented refresh.
- Local set membership is not treated as current authorization by itself.
19. A set is shared across threads while members are added and read. State what must be designed and how to test it.
Show hint
The local Set examples do not establish a concurrency contract.
Show worked solution
Choose an appropriate synchronization or ownership model for the shared operations, then test concurrent updates and reads in an isolated representative runtime. Specify what consistency callers require rather than inferring it from a sequential example.
Check your solution
- The design specifies synchronization or exclusive ownership.
- A concurrent test checks the required consistency.
20. Design a regression matrix for a set-backed import with duplicates, invalid IDs, normalization and independent value keys.
Show hint
Each requirement needs an observable outcome.
Show worked solution
Include empty input, repeated values, a normalization pair, an invalid identifier and equal independent keys. Assert membership and counts separately, report invalid data explicitly, and avoid depending on incidental set order.
Check your solution
- Membership, occurrence counts and invalid records are checked separately.
- The assertions do not depend on set inspection order.
Key takeaways
- A set represents unique membership.
- Keep hash-relevant keys stable.
- A set records membership, not occurrence frequency.
- Set difference is directional and mutation behavior depends on the operation.
- Stable equality and hash fields are necessary for reliable membership.