Sets
suggest changeA Set is an unordered collection of unique values. Use it when the questions you ask are "is this value in the collection?" or "which values do these two collections have in common?", and you don't care about duplicates or position.
tags = Set["ruby", "web", "ruby", "api"]
p tags # => Set["ruby", "web", "api"]
p tags.size # => 3
p tags.include?("web") # => true
p tags.include?("rails") # => false
Under the hood a Set stores its elements the same way a Hash stores keys, so membership checks take constant time no matter how big the set is. Array#include? has to scan the whole array.
In Ruby 4.0 Set is a core class written in C, so you don't need require "set". In older versions it was a standard library written in Ruby; since Ruby 3.2 it's loaded automatically on first use. Writing require "set" is still harmless, so code that has to run on old Rubies can keep it.
Creating sets
p Set.new # => Set[]
p Set.new([1, 2, 2, 3]) # => Set[1, 2, 3]
p Set[1, 2, 2, 3] # => Set[1, 2, 3]
p [3, 1, 3].to_set # => Set[3, 1]
p (1..5).to_set # => Set[1, 2, 3, 4, 5]
p "mississippi".chars.to_set # => Set["m", "i", "s", "p"]
p Set.new(nil) # => Set[]
Set.new accepts any enumerable, and an optional block that transforms each element before it's added:
p Set.new([1, 2, 3]) { |x| x * 10 } # => Set[10, 20, 30]
p Set.new(%w[a B c]) { it.downcase } # => Set["a", "b", "c"]
Set[...] is also how a set prints itself with p and inspect, so the output can be pasted back into Ruby.
Adding and removing elements
s = Set[1, 2]
s << 3 # alias of add
s.add(3) # already present, nothing happens
p s # => Set[1, 2, 3]
s.merge([4, 5], [6]) # add every element of one or more enumerables
p s # => Set[1, 2, 3, 4, 5, 6]
s.delete(6)
s.subtract([4, 5]) # remove every element of an enumerable
p s # => Set[1, 2, 3]
add, <<, delete, merge and subtract all return the set, so calls can be chained:
p Set[].add(1).add(2) << 3 # => Set[1, 2, 3]
The question-mark versions tell you whether anything changed. They return the set when it changed and nil when it didn't, which is handy for "do this only the first time" logic:
seen = Set[]
%w[a b a c b].each do |id|
if seen.add?(id)
puts "first time: #{id}"
else
puts "duplicate: #{id}"
end
end
first time: a
first time: b
duplicate: a
first time: c
duplicate: b
delete? works the same way: it returns nil if the element wasn't there.
s = Set[1, 2]
p s.delete?(1) # => Set[2]
p s.delete?(1) # => nil
To remove elements by condition there are delete_if, reject!, select! (alias filter!), keep_if and clear:
s = Set[1, 2, 3, 4, 5, 6]
s.delete_if(&:even?)
p s # => Set[1, 3, 5]
s.keep_if { it > 1 }
p s # => Set[3, 5]
s.clear
p s # => Set[]
Membership
include? has the aliases member? and ===. Because of === a set works directly in a case expression:
VOWELS = Set["a", "e", "i", "o", "u"]
def kind(ch)
case ch
when VOWELS then :vowel
when "a".."z" then :consonant
else :other
end
end
p kind("e") # => :vowel
p kind("x") # => :consonant
p kind("!") # => :other
It also works with grep, since grep uses ===:
words = %w[ant bee cat dog eel]
banned = Set["cat", "dog"]
p words.grep(banned) # => ["cat", "dog"]
p words.grep_v(banned) # => ["ant", "bee", "eel"]
Why not just use an array?
For a handful of elements an array is fine. For lookups in a large collection the difference is dramatic:
require "benchmark"
arr = (1..10_000).to_a
set = arr.to_set
Benchmark.bm(6) do |b|
b.report("Array") { 10_000.times { |i| arr.include?(i) } }
b.report("Set") { 10_000.times { |i| set.include?(i) } }
end
user system total real
Array 0.125426 0.001587 0.127013 ( 0.127020)
Set 0.000398 0.000000 0.000398 ( 0.000398)
That's about 300 times faster, and the gap grows with the size of the collection. A typical place this matters is filtering one large list by another:
users = [{ id: 1, name: "Ann" }, { id: 2, name: "Bob" }, { id: 3, name: "Cy" }]
blocked_ids = [2, 3].to_set # build the set once, outside the loop
p users.reject { blocked_ids.include?(it[:id]) }
# => [{id: 1, name: "Ann"}]
Converting to a set only pays off if you do many lookups. For a single include? call, building the set costs more than scanning the array once.
Set operations
Sets support the usual mathematical operations. Each returns a new set and leaves the operands unchanged. The argument can be any enumerable, not just a set.
a = Set[1, 2, 3, 4]
b = Set[3, 4, 5]
p a | b # => Set[1, 2, 3, 4, 5] union (alias: +, union)
p a & b # => Set[3, 4] intersection (alias: intersection)
p a - b # => Set[1, 2] difference (alias: difference)
p a ^ b # => Set[1, 2, 5] symmetric difference: in exactly one of them
p a | [9, 10] # => Set[1, 2, 3, 4, 9, 10]
Arrays have |, & and - too (see Arrays union intersection and difference), but they keep order, they're slower for large inputs, and - keeps duplicates from the left side. Arrays have no ^.
A practical example, comparing two versions of a configuration:
old_keys = Set[:host, :port, :user, :timeout]
new_keys = Set[:host, :port, :password, :retries]
puts "added: #{(new_keys - old_keys).to_a.inspect}"
puts "removed: #{(old_keys - new_keys).to_a.inspect}"
puts "kept: #{(old_keys & new_keys).to_a.inspect}"
added: [:password, :retries]
removed: [:user, :timeout]
kept: [:host, :port]
Comparing sets
Two sets are equal when they contain the same elements, regardless of order:
p Set[1, 2, 3] == Set[3, 2, 1] # => true
p Set[1, 2] == [1, 2] # => false, an array is never equal to a set
Subset and superset checks have both method and operator forms:
small = Set[1, 2]
big = Set[1, 2, 3]
p small.subset?(big) # => true (<=)
p small <= big # => true
p small < big # => true proper subset: subset and not equal
p big.superset?(small) # => true (>=)
p big > small # => true proper superset
p small.proper_subset?(small) # => false
p small <=> big # => -1
p big <=> small # => 1
p small <=> Set[1, 2] # => 0
p small <=> Set[7] # => nil, neither contains the other
The comparison operators need a set on the right; passing an array raises ArgumentError: value must be a set. disjoint? and intersect? are more forgiving and accept any enumerable:
p Set[1, 2].disjoint?([3, 4]) # => true, nothing in common
p Set[1, 2].intersect?([2, 9]) # => true
A common use is checking permissions:
required = Set[:read, :write]
granted = Set[:read, :write, :admin]
p required.subset?(granted) # => true, every required permission is granted
p (required - granted).empty? # => true, same thing written another way
Iterating and Enumerable
Set includes Enumerable, so each, map, select, sort, min, sum, group_by and the rest all work. Iteration follows insertion order, but don't rely on order as part of a set's meaning: two sets with different order are still equal.
Most Enumerable methods return arrays, not sets:
s = Set[3, 1, 4, 1, 5, 9, 2, 6]
p s.map { it * 2 } # => [6, 2, 8, 10, 18, 4, 12]
p s.sort # => [1, 2, 3, 4, 5, 6, 9]
p s.min, s.max, s.sum # => 1, 9, 30
p s.select(&:even?) # => [4, 2, 6]
p s.reject(&:even?) # => [3, 1, 5, 9]
p s.partition(&:even?) # => [[4, 2, 6], [3, 1, 5, 9]]
Even select, filter and reject return arrays, since they come from Enumerable. If you need a set back, call to_set on the result, or use in-place versions like select! and map! (alias collect!):
s = Set[1, 2, 3]
p s.map { it % 2 }.to_set # => Set[1, 0]
s.map! { it * 10 }
p s # => Set[10, 20, 30]
Sets have two grouping helpers that return sets. classify groups elements into a hash of sets; divide returns a set of sets:
files = Set["a.rb", "b.py", "c.rb", "d.md"]
p files.classify { File.extname(it) }
# => {".rb" => Set["a.rb", "c.rb"], ".py" => Set["b.py"], ".md" => Set["d.md"]}
p Set[1, 2, 3, 4, 5].divide(&:odd?)
# => Set[Set[1, 3, 5], Set[2, 4]]
flatten merges nested sets (but not nested arrays):
p Set[1, Set[2, Set[3]]].flatten # => Set[1, 2, 3]
p Set[1, [2, 3]].flatten # => Set[1, [2, 3]]
Converting
s = Set["b", "a", "c"]
p s.to_a # => ["b", "a", "c"]
p s.sort # => ["a", "b", "c"]
p s.join(", ") # => "b, a, c"
p s.to_set.equal?(s) # => true, to_set on a set returns itself
p Set[[:a, 1], [:b, 2]].to_h # => {a: 1, b: 2}
There's no SortedSet. It was removed from the standard library in Ruby 3.0 (it lives on in the sorted_set gem). If you need sorted output, call sort when you read the set.
JSON has no set type, and the json library turns a Set into the string from to_s, which is almost never what you want. Convert to an array first (see JSON with Ruby):
require "json"
s = Set[1, 2, 3]
p s.to_json # => "\"Set[1, 2, 3]\""
p s.to_a.to_json # => "[1,2,3]"
p JSON.parse("[1,2,3]").to_set # => Set[1, 2, 3]
How uniqueness is decided
A set considers two elements the same when they have equal hash values and eql? returns true, exactly like hash keys. That has a few consequences.
eql? is stricter than == for numbers, so 1 and 1.0 are different elements:
p 1 == 1.0 # => true
p 1.eql?(1.0) # => false
p Set[1, 1.0, 1r].size # => 3
Plain objects are compared by identity, so two objects with the same contents are both kept:
class Point
attr_reader :x, :y
def initialize(x, y) = (@x, @y = x, y)
end
p Set[Point.new(1, 2), Point.new(1, 2)].size # => 2
To make them compare by value, define eql? and hash (see Overriding hash function):
class Point
def eql?(other) = other.is_a?(Point) && x == other.x && y == other.y
alias == eql?
def hash = [x, y].hash
end
p Set[Point.new(1, 2), Point.new(1, 2)].size # => 1
Struct and Data classes already define value-based eql? and hash, so they work in sets without extra code:
Coord = Data.define(:x, :y)
p Set[Coord.new(x: 1, y: 2), Coord.new(x: 1, y: 2)]
# => Set[#<data Coord x=1, y=2>]
Sets themselves are hashable by contents, so a set can be an element of another set or a hash key:
visited = { Set[1, 2] => "pair" }
p visited[Set[2, 1]] # => "pair"
Don't mutate elements
Because elements are stored by their hash, changing an element after adding it breaks lookups. The element is still in the set, but include? can't find it:
key = [1]
s = Set[key]
key << 2
p s # => Set[[1, 2]]
p s.include?([1, 2]) # => false
s.reset # rebuild the internal hash table
p s.include?([1, 2]) # => true
Use immutable elements (numbers, symbols, frozen strings, Data) where you can. Strings are handled for you: like hash keys, unfrozen strings are copied and frozen when added, so changing the original doesn't affect the set:
name = +"bob"
s = Set[name]
name << "by"
p s # => Set["bob"]
p s.first.frozen? # => true
Identity sets
compare_by_identity switches a set to compare elements by object identity (equal?) instead of eql?, just like Hash#compare_by_identity. It's useful for tracking specific objects, for example to detect cycles while walking a graph:
a = "x"
b = "x"
s = Set[].compare_by_identity
s << a << b
p s.size # => 2, same contents but different objects
p s.compare_by_identity? # => true
Freezing
A frozen set raises FrozenError on any change, which makes it a good choice for constants:
ALLOWED_METHODS = Set["GET", "POST", "PUT", "DELETE"].freeze
p ALLOWED_METHODS.include?("GET") # => true
begin
ALLOWED_METHODS << "TRACE"
rescue FrozenError => e
puts e.message
end
can't modify frozen Set: Set["GET", "POST", "PUT", "DELETE"]
Example: finding duplicates and unique words
Sets make a lot of small data-processing jobs short. For just removing duplicates from an array, uniq is enough (see Get unique array elements); sets help when you also need to track what you've seen as you go:
def duplicates(items)
seen = Set[]
dups = Set[]
items.each { |x| dups << x unless seen.add?(x) }
dups
end
p duplicates(%w[a b a c b a]) # => Set["a", "b"]
Comparing the vocabulary of two texts:
def words(text) = text.downcase.scan(/[a-z']+/).to_set
a = words("The quick brown fox jumps over the lazy dog")
b = words("The lazy cat sleeps over the warm dog bed")
p a & b # => Set["the", "lazy", "over", "dog"]
p (a ^ b).size # => 8
similarity = (a & b).size.fdiv((a | b).size)
puts "Jaccard similarity: #{similarity.round(2)}"
Jaccard similarity: 0.33
Summary
| Task | Code |
|---|---|
| Create | Set[1, 2], Set.new(enum), enum.to_set |
| Add / remove | <<, add, add?, merge, delete, delete?, subtract |
| Test membership | include?, member?, === |
| Union, intersection, difference | |, &, -, ^ |
| Subset / superset | subset? (<=), <, superset? (>=), >, disjoint?, intersect? |
| Group | classify, divide |
| Convert | to_a, sort, to_set |
Reach for a Set whenever you check membership repeatedly, need to deduplicate as you go, or want to compare collections as groups rather than as ordered lists.