# struct Set(T)

- Set(T)
- Struct
- Value
- Object

##
Overview

`Set` implements a collection of unordered values with no duplicates.

An `Enumerable` object can be converted to `Set` using the `#to_set` method.

`Set` uses `Hash` as storage, so you must note the following points:

- Equality of elements is determined according to `Object#==` and `Object#hash`.
- `Set` assumes that the identity of each element does not change while it is stored. Modifying an element of a set will render the set to an unreliable state.

###
Example

    s1 = Set{1, 2}
    s2 = [1, 2].to_set
    s3 = Set.new [1, 2]
    s1 == s2 # => true
    s1 == s3 # => true
    s1.add(2)
    s1.concat([6, 8])
    s1.subset_of? s2 # => false
    s2.subset_of? s1 # => true

##
Included Modules

- Enumerable(T)
- Iterable(T)

##
Defined in:

json/to_json.cr
set.cr
yaml/to_yaml.cr

##
Constructors

- .additive_identity : self

  Returns the additive identity of this type.

- .new(ctx : YAML::ParseContext, node : YAML::Nodes::Node)
- .new(other : Indexable(T))

  Optimized version of `.new` used when other is also an `Indexable`

- .new(enumerable : Enumerable(T))

  Creates a new set from the elements in enumerable.

- .new(pull : JSON::PullParser)
- .new(initial_capacity = nil)

  Creates a new, empty `Set`.

- .new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &)

##
Instance Method Summary

- #&(other : Set) : Set(T)

  Intersection: returns a new set containing elements common to both sets.

- #+(other : Set(U)) : Set(T | U) forall U

  Addition: returns a new set containing the unique elements from both sets.

- #-(other : Set) : Set(T)

  Difference: returns a new set containing elements in this set that are not present in the other.

- #-(other : Enumerable) : Set(T)

  Difference: returns a new set containing elements in this set that are not present in the other enumerable.

- #<<(object : T) : self

  Alias for `#add`

- #==(other : Set) : Bool

  Returns `true` if both sets have the same elements.

- #===(object : T) : Bool

  Same as `#includes?`.

- #^(other : Set(U)) : Set(T | U) forall U

  Symmetric Difference: returns a new set `(self - other) | (other - self)`.

- #^(other : Enumerable(U)) : Set(T | U) forall U

  Symmetric Difference: returns a new set `(self - other) | (other - self)`.

- #|(other : Set(U)) : Set(T | U) forall U

  Union: returns a new set containing all unique elements from both sets.

- #add(object : T) : self

  Adds object to the set and returns `self`.

- #add?(object : T) : Bool

  Adds object to the set and returns `true` on success and `false` if the value was already in the set.

- #clear : self

  Removes all elements in the set, and returns `self`.

- #clone : Set(T)

  Returns a new `Set` with all of the elements cloned.

- #compare_by_identity : self

  Makes this set compare objects using their object identity (`object_id)` for types that define such method (`Reference` types, but also structs that might wrap other `Reference` types and delegate the `object_id` method to them).

- #compare_by_identity? : Bool

  Returns `true` if this Set is comparing objects by `object_id`.

- #concat(elems) : self

  Adds `#each` element of elems to the set and returns `self`.

- #delete(object) : Bool

  Removes the object from the set and returns `true` if it was present, otherwise returns `false`.

- #dup : Set(T)

  Returns a new `Set` with all of the same elements.

- #each(& : T -> ) : Nil

  Yields each element of the set, and returns `nil`.

- #each

  Returns an iterator for each element of the set.

- #empty? : Bool

  Returns `true` if the set is empty.

- #hash(hasher)

  See `Object#hash(hasher)`

- #includes?(object) : Bool

  Returns `true` if object exists in the set.

- #inspect(io : IO) : Nil

  Alias of `#to_s`.

- #intersects?(other : Set) : Bool

  Returns `true` if the set and the given set have at least one element in common.

- #pretty_print(pp) : Nil
- #proper_subset_of?(other : Set) : Bool

  Returns `true` if the set is a proper subset of the other set.

- #proper_superset_of?(other : Set) : Bool

  Returns `true` if the set is a superset of the other set.

- #rehash : Nil

  Rebuilds the set based on the current elements.

- #reject!(& : T -> ) : self

  Deletes every element of the set for which the block is truthy, and returns `self`.

- #select!(& : T -> ) : self

  Deletes every element of the set for which the block is falsey, and returns `self`.

- #size : Int32

  Returns the number of elements in the set.

- #subset_of?(other : Set) : Bool

  Returns `true` if the set is a subset of the other set.

- #subtract(other : Enumerable) : self

  Returns `self` after removing from it those elements that are present in the given enumerable.

- #superset_of?(other : Set) : Bool

  Returns `true` if the set is a superset of the other set.

- #to_a : Array(T)

  Returns the elements as an `Array`.

- #to_a(& : T -> U) : Array(U) forall U

  Returns an `Array` with the results of running block against each element of the collection.

- #to_json(json : JSON::Builder) : Nil
- #to_s(io : IO) : Nil

  Writes a string representation of the set to io.

- #to_yaml(yaml : YAML::Nodes::Builder) : Nil

### Instance methods inherited from module `Iterable(T)`

chunk(reuse = false, &block : T -> U) forall U chunk, chunk_while(reuse : Bool | Array(T) = false, &block : T, T -> B) forall B chunk_while, cycle(n)
cycle cycle, each each, each_cons(count : Int, reuse = false) each_cons, each_cons_pair each_cons_pair, each_slice(count : Int, reuse = false) each_slice, each_step(n : Int)
each_step(n : Int, *, offset : Int) each_step, each_with_index(offset = 0) each_with_index, each_with_object(obj) each_with_object, slice_after(reuse : Bool | Array(T) = false, &block : T -> B) forall B
slice_after(pattern, reuse : Bool | Array(T) = false) slice_after, slice_before(reuse : Bool | Array(T) = false, &block : T -> B) forall B
slice_before(pattern, reuse : Bool | Array(T) = false) slice_before, slice_when(reuse : Bool | Array(T) = false, &block : T, T -> B) forall B slice_when

### Instance methods inherited from module `Enumerable(T)`

accumulate(initial : U) : Array(U) forall U
accumulate : Array(T)
accumulate(initial : U, &block : U, T -> U) : Array(U) forall U
accumulate(&block : T, T -> T) : Array(T) accumulate, all?(& : T -> ) : Bool
all?(pattern) : Bool
all? : Bool all?, any?(& : T -> ) : Bool
any?(pattern) : Bool
any? : Bool any?, chunks(&block : T -> U) forall U chunks, compact_map(& : T -> _) compact_map, count(& : T -> ) : Int32
count(item) : Int32 count, cycle(n, & : T -> ) : Nil
cycle(& : T -> ) : Nil cycle, each(& : T -> ) each, each_cons(count : Int, reuse = false, &) each_cons, each_cons_pair(& : T, T -> ) : Nil each_cons_pair, each_slice(count : Int, reuse = false, &) each_slice, each_step(n : Int, *, offset : Int = 0, & : T -> ) : Nil each_step, each_with_index(offset = 0, &) each_with_index, each_with_object(obj : U, & : T, U -> ) : U forall U each_with_object, empty? : Bool empty?, find(if_none = nil, & : T -> ) find, find!(& : T -> ) : T find!, find_value(if_none = nil, & : T -> ) find_value, first(&)
first(count : Int) : Array(T)
first : T first, first? : T | Nil first?, flat_map(& : T -> _) flat_map, group_by(& : T -> U) forall U group_by, in_groups_of(size : Int, filled_up_with : U = nil) forall U
in_groups_of(size : Int, filled_up_with : U = nil, reuse = false, &) forall U in_groups_of, in_slices_of(size : Int) : Array(Array(T)) in_slices_of, includes?(obj) : Bool includes?, index(& : T -> ) : Int32 | Nil
index(obj) : Int32 | Nil index, index!(& : T -> ) : Int32
index!(obj) : Int32 index!, index_by(& : T -> U) : Hash(U, T) forall U index_by, join(io : IO, separator = "") : Nil
join(separator, io : IO) : Nil
join(separator = "") : String
join(io : IO, separator = "", & : T, IO -> )
join(separator, io : IO, &)
join(separator = "", & : T -> ) join, map(& : T -> U) : Array(U) forall U map, map_with_index(offset = 0, & : T, Int32 -> U) : Array(U) forall U map_with_index, max(count : Int) : Array(T)
max : T max, max? : T | Nil max?, max_by(& : T -> U) : T forall U max_by, max_by?(& : T -> U) : T | Nil forall U max_by?, max_of(& : T -> U) : U forall U max_of, max_of?(& : T -> U) : U | Nil forall U max_of?, min(count : Int) : Array(T)
min : T min, min? : T | Nil min?, min_by(& : T -> U) : T forall U min_by, min_by?(& : T -> U) : T | Nil forall U min_by?, min_of(& : T -> U) : U forall U min_of, min_of?(& : T -> U) : U | Nil forall U min_of?, minmax : Tuple(T, T) minmax, minmax? : Tuple(T | Nil, T | Nil) minmax?, minmax_by(& : T -> U) : Tuple(T, T) forall U minmax_by, minmax_by?(& : T -> U) : Tuple(T, T) | Tuple(Nil, Nil) forall U minmax_by?, minmax_of(& : T -> U) : Tuple(U, U) forall U minmax_of, minmax_of?(& : T -> U) : Tuple(U, U) | Tuple(Nil, Nil) forall U minmax_of?, none?(& : T -> ) : Bool
none?(pattern) : Bool
none? : Bool none?, one?(& : T -> ) : Bool
one?(pattern) : Bool
one? : Bool one?, partition(& : T -> ) : Tuple(Array(T), Array(T))
partition(type : U.class) forall U partition, present? : Bool present?, product(initial : Number)
product
product(initial : Number, & : T -> )
product(& : T -> _) product, reduce(memo, &)
reduce(&) reduce, reduce?(&) reduce?, reject(& : T -> )
reject(type : U.class) forall U
reject(pattern) : Array(T) reject, sample(n : Int, random : Random = Random::DEFAULT) : Array(T)
sample(random : Random = Random::DEFAULT) : T sample, select(& : T -> )
select(type : U.class) : Array(U) forall U
select(pattern) : Array(T) select, size : Int32 size, skip(count : Int) skip, skip_while(& : T -> ) : Array(T) skip_while, sum(initial)
sum
sum(initial, & : T -> )
sum(& : T -> ) sum, take_while(& : T -> ) : Array(T) take_while, tally(hash)
tally : Hash(T, Int32) tally, tally_by(hash, &)
tally_by(&block : T -> U) : Hash(U, Int32) forall U tally_by, to_a : Array(T)
to_a(& : T -> U) : Array(U) forall U to_a, to_h
to_h(& : T -> Tuple(K, V)) forall K, V to_h, to_set : Set(T)
to_set(&block : T -> U) : Set(U) forall U to_set, zip(*others : Indexable | Iterable | Iterator, &)
zip(*others : Indexable | Iterable | Iterator) zip, zip?(*others : Indexable | Iterable | Iterator, &)
zip?(*others : Indexable | Iterable | Iterator) zip?

### Class methods inherited from module `Enumerable(T)`

element_type(x) element_type

### Instance methods inherited from struct `Struct`

==(other : YAML::Any)
==(other) : Bool ==, hash(hasher) hash, inspect(io : IO) : Nil inspect, pretty_print(pp) : Nil pretty_print, to_s(io : IO) : Nil to_s

### Class methods inherited from struct `Struct`

pre_initialize(address : Pointer) : Nil pre_initialize

### Instance methods inherited from struct `Value`

==(other : Log::Metadata::Value)
==(other : JSON::Any)
==(other : YAML::Any)
==(other) ==, dup dup

### Instance methods inherited from class `Object`

! : Bool !, !=(other) !=, !~(other) !~, ==(other) ==, ===(other : JSON::Any)
===(other : YAML::Any)
===(other) ===, =~(other) =~, as(type : Class) as, as?(type : Class) as?, class class, dup dup, hash(hasher)
hash hash, in?(collection : Object) : Bool
in?(*values : Object) : Bool in?, inspect(io : IO) : Nil
inspect : String inspect, is_a?(type : Class) : Bool is_a?, itself itself, nil? : Bool nil?, not_nil!(message)
not_nil! not_nil!, pretty_inspect(width = 79, newline = "\n", indent = 0) : String pretty_inspect, pretty_print(pp : PrettyPrint) : Nil pretty_print, responds_to?(name : Symbol) : Bool responds_to?, tap(&) tap, to_json(io : IO) : Nil
to_json : String to_json, to_pretty_json(indent : String = " ") : String
to_pretty_json(io : IO, indent : String = " ") : Nil to_pretty_json, to_s(io : IO) : Nil
to_s : String to_s, to_yaml(io : IO) : Nil
to_yaml : String to_yaml, try(&) try, unsafe_as(type : T.class) forall T unsafe_as

### Class methods inherited from class `Object`

from_json(string_or_io : String | IO, root : String)
from_json(string_or_io : String | IO) from_json, from_yaml(string_or_io : String | IO) from_yaml

### Macros inherited from class `Object`

class_getter(*names, &block) class_getter, class_getter!(*names) class_getter!, class_getter?(*names, &block) class_getter?, class_property(*names, &block) class_property, class_property!(*names) class_property!, class_property?(*names, &block) class_property?, class_setter(*names) class_setter, def_clone def_clone, def_equals(*fields) def_equals, def_equals_and_hash(*fields) def_equals_and_hash, def_hash(*fields) def_hash, delegate(*methods, to object) delegate, forward_missing_to(delegate) forward_missing_to, getter(*names, &block) getter, getter!(*names) getter!, getter?(*names, &block) getter?, property(*names, &block) property, property!(*names) property!, property?(*names, &block) property?, setter(*names) setter

##
Constructor Detail

def self.additive_identity : self #

Returns the additive identity of this type.

This is an empty set.

def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node) #
def self.new(other : Indexable(T)) #

Optimized version of `.new` used when other is also an `Indexable`

def self.new(enumerable : Enumerable(T)) #

Creates a new set from the elements in enumerable.

    a = [1, 3, 5]
    s = Set.new a
    s.empty? # => false

def self.new(pull : JSON::PullParser) #
def self.new(initial_capacity = nil) #

Creates a new, empty `Set`.

    s = Set(Int32).new
    s.empty? # => true

An initial capacity can be specified, and it will be set as the initial capacity of the internal `Hash`.

def self.new(ctx : YAML::ParseContext, node : YAML::Nodes::Node, &) #

##
Instance Method Detail

def &(other : Set) : Set(T) #

Intersection: returns a new set containing elements common to both sets.

    Set{1, 1, 3, 5} & Set{1, 2, 3}               # => Set{1, 3}
    Set{'a', 'b', 'b', 'z'} & Set{'a', 'b', 'c'} # => Set{'a', 'b'}

def +(other : Set(U)) : Set(T | U) forall U #

Addition: returns a new set containing the unique elements from both sets.

    Set{1, 1, 2, 3} + Set{3, 4, 5} # => Set{1, 2, 3, 4, 5}

def -(other : Set) : Set(T) #

Difference: returns a new set containing elements in this set that are not present in the other.

    Set{1, 2, 3, 4, 5} - Set{2, 4}               # => Set{1, 3, 5}
    Set{'a', 'b', 'b', 'z'} - Set{'a', 'b', 'c'} # => Set{'z'}

def -(other : Enumerable) : Set(T) #

Difference: returns a new set containing elements in this set that are not present in the other enumerable.

    Set{1, 2, 3, 4, 5} - [2, 4]               # => Set{1, 3, 5}
    Set{'a', 'b', 'b', 'z'} - ['a', 'b', 'c'] # => Set{'z'}

def <<(object : T) : self #

Alias for `#add`

def ==(other : Set) : Bool #

Returns `true` if both sets have the same elements.

    Set{1, 5} == Set{1, 5} # => true

def ===(object : T) : Bool #

Same as `#includes?`.

It is for convenience with using on `case` statement.

    red_like = Set{"red", "pink", "violet"}
    blue_like = Set{"blue", "azure", "violet"}

    case "violet"
    when red_like & blue_like
      puts "red & blue like color!"
    when red_like
      puts "red like color!"
    when blue_like
      puts "blue like color!"
    end

See also: `Object#===`.

def ^(other : Set(U)) : Set(T | U) forall U #

Symmetric Difference: returns a new set `(self - other) | (other - self)`. Equivalently, returns `(self | other) - (self & other)`.

    Set{1, 2, 3, 4, 5} ^ Set{2, 4, 6}            # => Set{1, 3, 5, 6}
    Set{'a', 'b', 'b', 'z'} ^ Set{'a', 'b', 'c'} # => Set{'z', 'c'}

def ^(other : Enumerable(U)) : Set(T | U) forall U #

Symmetric Difference: returns a new set `(self - other) | (other - self)`. Equivalently, returns `(self | other) - (self & other)`.

    Set{1, 2, 3, 4, 5} ^ [2, 4, 6]            # => Set{1, 3, 5, 6}
    Set{'a', 'b', 'b', 'z'} ^ ['a', 'b', 'c'] # => Set{'z', 'c'}

def |(other : Set(U)) : Set(T | U) forall U #

Union: returns a new set containing all unique elements from both sets.

    Set{1, 1, 3, 5} | Set{1, 2, 3}               # => Set{1, 3, 5, 2}
    Set{'a', 'b', 'b', 'z'} | Set{'a', 'b', 'c'} # => Set{'a', 'b', 'z', 'c'}

See also: `#concat` to add elements from a set to `self`.

def add(object : T) : self #

Adds object to the set and returns `self`.

    s = Set{1, 5}
    s.includes? 8 # => false
    s.add(8)
    s.includes? 8 # => true

def add?(object : T) : Bool #

Adds object to the set and returns `true` on success and `false` if the value was already in the set.

    s = Set{1, 5}
    s.add? 8 # => true
    s.add? 8 # => false

def clear : self #

Removes all elements in the set, and returns `self`.

    s = Set{1, 5}
    s.size # => 2
    s.clear
    s.size # => 0

def clone : Set(T) #

Returns a new `Set` with all of the elements cloned.

def compare_by_identity : self #

Makes this set compare objects using their object identity (`object_id)` for types that define such method (`Reference` types, but also structs that might wrap other `Reference` types and delegate the `object_id` method to them).

    s = Set{"foo", "bar"}
    s.includes?("fo" + "o") # => true

    s.compare_by_identity
    s.compare_by_identity?  # => true
    s.includes?("fo" + "o") # => false # not the same String instance

def compare_by_identity? : Bool #

Returns `true` if this Set is comparing objects by `object_id`.

See `#compare_by_identity`.

def concat(elems) : self #

Adds `#each` element of elems to the set and returns `self`.

    s = Set{1, 5}
    s.concat [5, 5, 8, 9]
    s.size # => 4

See also: `#|` to merge two sets and return a new one.

def delete(object) : Bool #

Removes the object from the set and returns `true` if it was present, otherwise returns `false`.

    s = Set{1, 5}
    s.includes? 5 # => true
    s.delete 5    # => true
    s.includes? 5 # => false
    s.delete 5    # => false

def dup : Set(T) #

Returns a new `Set` with all of the same elements.

def each(& : T -> ) : Nil #

Yields each element of the set, and returns `nil`.

def each #

Returns an iterator for each element of the set.

def empty? : Bool #

Returns `true` if the set is empty.

    s = Set(Int32).new
    s.empty? # => true
    s << 3
    s.empty? # => false

def hash(hasher) #

See `Object#hash(hasher)`

def includes?(object) : Bool #

Returns `true` if object exists in the set.

    s = Set{1, 5}
    s.includes? 5 # => true
    s.includes? 9 # => false

def inspect(io : IO) : Nil #

Alias of `#to_s`.

def intersects?(other : Set) : Bool #

Returns `true` if the set and the given set have at least one element in common.

    Set{1, 2, 3}.intersects? Set{4, 5} # => false
    Set{1, 2, 3}.intersects? Set{3, 4} # => true

def pretty_print(pp) : Nil #
def proper_subset_of?(other : Set) : Bool #

Returns `true` if the set is a proper subset of the other set.

This set must have fewer elements than the other set, and all of elements in this set must be present in the other set.

    Set{1, 5}.proper_subset_of? Set{1, 3, 5}    # => true
    Set{1, 3, 5}.proper_subset_of? Set{1, 3, 5} # => false

def proper_superset_of?(other : Set) : Bool #

Returns `true` if the set is a superset of the other set.

The other must have fewer elements than this set, and all of elements in the other set must be present in this set.

    Set{1, 3, 5}.proper_superset_of? Set{1, 5}    # => true
    Set{1, 3, 5}.proper_superset_of? Set{1, 3, 5} # => false

def rehash : Nil #

Rebuilds the set based on the current elements.

When using mutable data types as elements, modifying an elements after it was inserted into the `Set` may lead to undefined behaviour. This method re-indexes the set using the current elements.

def reject!(& : T -> ) : self #

Deletes every element of the set for which the block is truthy, and returns `self`.

def select!(& : T -> ) : self #

Deletes every element of the set for which the block is falsey, and returns `self`.

def size : Int32 #

Returns the number of elements in the set.

    s = Set{1, 5}
    s.size # => 2

def subset_of?(other : Set) : Bool #

Returns `true` if the set is a subset of the other set.

This set must have the same or fewer elements than the other set, and all of elements in this set must be present in the other set.

    Set{1, 5}.subset_of? Set{1, 3, 5}    # => true
    Set{1, 3, 5}.subset_of? Set{1, 3, 5} # => true

def subtract(other : Enumerable) : self #

Returns `self` after removing from it those elements that are present in the given enumerable.

    Set{'a', 'b', 'b', 'z'}.subtract Set{'a', 'b', 'c'} # => Set{'z'}
    Set{1, 2, 3, 4, 5}.subtract [2, 4, 6]               # => Set{1, 3, 5}

def superset_of?(other : Set) : Bool #

Returns `true` if the set is a superset of the other set.

The other must have the same or fewer elements than this set, and all of elements in the other set must be present in this set.

    Set{1, 3, 5}.superset_of? Set{1, 5}    # => true
    Set{1, 3, 5}.superset_of? Set{1, 3, 5} # => true

def to_a : Array(T) #

Returns the elements as an `Array`.

    Set{1, 5}.to_a # => [1,5]

def to_a(& : T -> U) : Array(U) forall U #

Returns an `Array` with the results of running block against each element of the collection.

    Set{1, 2, 3, 4, 5}.to_a { |i| i // 2 } # => [0, 1, 1, 2, 2]

def to_json(json : JSON::Builder) : Nil #
def to_s(io : IO) : Nil #

Writes a string representation of the set to io.

def to_yaml(yaml : YAML::Nodes::Builder) : Nil #