# set.rb - defines the Set class
# Copyright (c) 2002-2008 Akinori MUSHA <knu@iDaemons.org>
# Documentation by Akinori MUSHA and Gavin Sinclair.
# All rights reserved. You can redistribute and/or modify it under the same
# $Id: set.rb 17051 2008-06-09 09:20:43Z knu $
# This library provides the Set class, which deals with a collection
# of unordered values with no duplicates. It is a hybrid of Array's
# intuitive inter-operation facilities and Hash's fast lookup. If you
# need to keep values ordered, use the SortedSet class.
# The method +to_set+ is added to Enumerable for convenience.
# See the Set class for an example of usage.
# Set implements a collection of unordered values with no duplicates.
# This is a hybrid of Array's intuitive inter-operation facilities and
# Several methods accept any Enumerable object (implementing +each+)
# for greater flexibility: new, replace, merge, subtract, |, &, -, ^.
# The equality of each couple of elements is determined according to
# Object#eql? and Object#hash, since Set uses Hash as storage.
# Finally, if you are using class Set, you can also use Enumerable#to_set
# s1 = Set.new [1, 2] # -> #<Set: {1, 2}>
# s2 = [1, 2].to_set # -> #<Set: {1, 2}>
# s1.add("foo") # -> #<Set: {1, 2, "foo"}>
# s1.merge([2, 6]) # -> #<Set: {6, 1, 2, "foo"}>
# s1.subset? s2 # -> false
# s2.subset? s1 # -> true
# - Akinori MUSHA <knu@iDaemons.org> (current maintainer)
# Creates a new set containing the given objects.
# Creates a new set containing the elements of the given enumerable
# If a block is given, the elements of enum are preprocessed by the
def initialize(enum = nil, &block) # :yields: o
enum.each { |o| add(block[o]) }
def initialize_copy(orig)
@hash = orig.instance_eval{@hash}.dup
# Returns the number of elements.
# Returns true if the set contains no elements.
# Removes all elements and returns self.
# Replaces the contents of the set with the contents of the given
# enumerable object and returns self.
if enum.class == self.class
@hash.replace(enum.instance_eval { @hash })
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# Converts the set to an array. The order of elements is uncertain.
def flatten_merge(set, seen = Set.new)
if seen.include?(e_id = e.object_id)
raise ArgumentError, "tried to flatten recursive Set"
# Returns a new set that is a copy of the set, flattening each
# containing set recursively.
self.class.new.flatten_merge(self)
# Equivalent to Set#flatten, but replaces the receiver with the
# result in place. Returns nil if no modifications were made.
if detect { |e| e.is_a?(Set) }
# Returns true if the set contains the given object.
# Returns true if the set is a superset of the given set.
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size < set.size
set.all? { |o| include?(o) }
# Returns true if the set is a proper superset of the given set.
def proper_superset?(set)
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if size <= set.size
set.all? { |o| include?(o) }
# Returns true if the set is a subset of the given set.
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size < size
all? { |o| set.include?(o) }
# Returns true if the set is a proper subset of the given set.
set.is_a?(Set) or raise ArgumentError, "value must be a set"
return false if set.size <= size
all? { |o| set.include?(o) }
# Calls the given block once for each element in the set, passing
# the element as parameter. Returns an enumerator if no block is
block_given? or return enum_for(__method__)
@hash.each_key { |o| yield(o) }
# Adds the given object to the set and returns self. Use +merge+ to
# add several elements at once.
# Adds the given object to the set and returns self. If the
# object is already in the set, returns nil.
# Deletes the given object from the set and returns self. Use +subtract+ to
# delete several items at once.
# Deletes the given object from the set and returns self. If the
# object is not in the set, returns nil.
# Deletes every element of the set for which block evaluates to
# true, and returns self.
to_a.each { |o| @hash.delete(o) if yield(o) }
# Do collect() destructively.
each { |o| set << yield(o) }
# Equivalent to Set#delete_if, but returns nil if no changes were
delete_if { |o| yield(o) }
# Merges the elements of the given enumerable object to the set and
@hash.update(enum.instance_eval { @hash })
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# Deletes every element that appears in the given enumerable object
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
enum.each { |o| delete(o) }
# Returns a new set built by merging the set and the elements of the
# given enumerable object.
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# Returns a new set built by duplicating the set, removing every
# element that appears in the given enumerable object.
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
# Returns a new set containing elements common to the set and the
# given enumerable object.
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
enum.each { |o| n.add(o) if include?(o) }
# Returns a new set containing elements exclusive between the set
# and the given enumerable object. (set ^ enum) is equivalent to
# ((set | enum) - (set & enum)).
enum.is_a?(Enumerable) or raise ArgumentError, "value must be enumerable"
each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
# Returns true if two sets are equal. The equality of each couple
# of elements is defined according to Object#eql?.
equal?(set) and return true
set.is_a?(Set) && size == set.size or return false
set.all? { |o| hash.include?(o) }
return false unless o.is_a?(Set)
@hash.eql?(o.instance_eval{@hash})
# Classifies the set by the return value of the given block and
# returns a hash of {value => set of elements} pairs. The block is
# called once for each element of the set, passing the element as
# files = Set.new(Dir.glob("*.rb"))
# hash = files.classify { |f| File.mtime(f).year }
# p hash # => {2000=>#<Set: {"a.rb", "b.rb"}>,
# # 2001=>#<Set: {"c.rb", "d.rb", "e.rb"}>,
# # 2002=>#<Set: {"f.rb"}>}
def classify # :yields: o
(h[x] ||= self.class.new).add(i)
# Divides the set into a set of subsets according to the commonality
# defined by the given block.
# If the arity of the block is 2, elements o1 and o2 are in common
# if block.call(o1, o2) is true. Otherwise, elements o1 and o2 are
# in common if block.call(o1) == block.call(o2).
# numbers = Set[1, 3, 4, 6, 9, 10, 11]
# set = numbers.divide { |i,j| (i - j).abs == 1 }
# p set # => #<Set: {#<Set: {1}>,
class << dig = {} # :nodoc:
alias tsort_each_node each_key
def tsort_each_child(node, &block)
each{ |v| func.call(u, v) and a << v }
dig.each_strongly_connected_component { |css|
set.add(self.class.new(css))
Set.new(classify(&func).values)
InspectKey = :__inspect_key__ # :nodoc:
# Returns a string containing a human-readable representation of the
# set. ("#<Set: {element1, element2, ...}>")
ids = (Thread.current[InspectKey] ||= [])
if ids.include?(object_id)
return sprintf('#<%s: {...}>', self.class.name)
return sprintf('#<%s: {%s}>', self.class, to_a.inspect[1..-2])
def pretty_print(pp) # :nodoc:
pp.text sprintf('#<%s: {', self.class.name)
def pretty_print_cycle(pp) # :nodoc:
pp.text sprintf('#<%s: {%s}>', self.class.name, empty? ? '' : '...')
# SortedSet implements a set which elements are sorted in order. See Set.
# a hack to shut up warning
alias old_init initialize
def initialize(*args, &block)
def initialize(*args, &block)
@keys = nil if @hash.size != n