Set (Ruby)

A Set is a collection of unique, unordered elements from the standard library. It offers fast membership tests and set operations like union, intersection, and difference.

Ruby

Set stores each element at most once, automatically discarding duplicates. After require "set", you build one with Set.new([1,2,2,3]) (which holds {1,2,3}) or array.to_set. Membership checks (set.include?(x)) are fast, like a hash, which is the main reason to use a Set over an Array.

Sets support mathematical operations with readable methods and operators: union (| or +), intersection (&), difference (-), and subset/superset tests (subset?, superset?). These make 'which items are in both / either / only one' queries concise.

Choose a Set when uniqueness and fast lookup matter and order doesn't; choose an Array when order or duplicates matter. Internally Set is backed by a Hash, so its elements must be hashable.

Syntax

require "set"
s = Set.new([1, 2, 3])
s.include?(2)

Examples

Ruby

require "set"
a = Set.new([1, 2, 3])
b = Set.new([2, 3, 4])
puts (a & b).to_a.sort.inspect
puts (a | b).to_a.sort.inspect
puts a.include?(2)

Output:

[2, 3]
[1, 2, 3, 4]
true

Learn it in a lesson

See also

Back to the Dictionary