A set is a collection of distinct objects. It rejects duplicates by value as well as by object identity, so equivalent strings or arrays appear only once. section 9.5
Create a set from a collection
Ruby provides Set.new rather than a set literal. Pass an array to insert its elements individually, or provide a block to transform each element first: Set.new(["David", "Amy"]) { |name| name.upcase } produces a set containing "DAVID" and "AMY". section 9.5.1
Manipulate set membership and relationships with these operations:
- Add one object with << or add; adding an existing or content-equal object leaves the set unchanged. section 9.5.2
- Remove an object with delete; deleting a missing object also leaves the set unchanged. section 9.5.2
- Use add? when the return value matters: it returns nil if the set was unchanged. section 9.5.2
- Combine sets or enumerable objects with union (+, |), intersection (&), difference (-), and exclusive union (^); these operations return new sets. section 9.5.2
- Use merge to extend the existing set in place, and use subset?, superset?, proper_subset, or proper_superset for containment tests between sets. section 9.5.2 section 9.5.3
>> tri_state = Set.new(["Connecticut", "New Jersey", "New York"])
=> #<Set: {"Connecticut", "New Jersey", "New York"}>
# Subtraction (difference/-)
>> state_set - tri_state
=> #<Set: {"Maine", "Massachusetts", "New Hampshire", "Rhode Island",
"Vermont"}>
# Addition (union/+/|)
>> state_set + tri_state
=> #<Set: {"Connecticut", "Maine", "Massachusetts", "New Hampshire",
"Rhode Island", "Vermont", "New Jersey", "New York"}>
# Intersection (&)
>> state_set & tri_state
=> #<Set: {"Connecticut"}>
>> state_set | tri_state
=> #<Set: {"Connecticut", "Maine", "Massachusetts", "New Hampshire",
"Rhode Island", "Vermont", "New Jersey", "New York"}>
Compare subtraction, union, and intersection on overlapping state sets to see how each operation selects elements. section 9.5.2
Sets complement arrays and hashes as a collection type for unique values and built-in set algebra. They belong to Ruby’s standard library, and their collection behavior connects to Enumerable and each-based iteration. section 9.6 section 9.0














