Set
A set holds each value once, in the order first added. Elements are Int, String or Bytes, like map keys. Sets are immutable.
forwalks a set in order. A set prints asSet[1, 2].a == bis true when the two sets have the same elements, in any order.- A set can be a struct field, a list item or a map value.
- A set is not JSON-encodable, so
JSON.encoderefuses it.
def main() -> Void
seen = Set.new(["b", "a", "b"])
for name in seen
puts(name)
end
puts(seen)
endb
a
Set["b", "a"]new #
Set.new(items: List[T]) -> Set[T]Builds a set from a list. A repeated item is dropped, and the first one keeps its place. T must be Int, String or Bytes, otherwise CHECK-SET-ELEMENT-TYPE. An empty list needs an expected type, like [] and {}: CHECK-EMPTY-SET-TYPE without one.
def main() -> Void
puts(Set.new([3, 1, 2, 3, 1]))
empty_set: Set[String] = Set.new([])
puts(empty_set)
endSet[3, 1, 2]
Set[]add #
Set.add(set: Set[T], value: T) -> Set[T]Adds an element at the end. A member leaves the set as it is.
def main() -> Void
s = Set.new([1, 2])
puts(s.add(3))
puts(s.add(1))
puts(s)
endSet[1, 2, 3]
Set[1, 2]
Set[1, 2]delete #
Set.delete(set: Set[T], value: T) -> Set[T]Removes an element. A missing element is fine. An element added again later goes to the end. It costs the same as Map.delete.
def main() -> Void
s = Set.new(["a", "b", "c"])
puts(s.delete("a"))
puts(s.delete("zzz"))
puts(s.delete("a").add("a"))
endSet["b", "c"]
Set["a", "b", "c"]
Set["b", "c", "a"]include? #
Set.include?(set: Set[T], value: T) -> BoolTests membership. It takes effectively constant time, like Map.key?.
def main() -> Void
s = Set.new([1, 2])
puts(s.include?(2))
puts(s.include?(5))
endtrue
falsesize and empty? #
Set.size(set: Set[T]) -> Int
Set.empty?(set: Set[T]) -> Booldef main() -> Void
s = Set.new([4, 4, 5])
puts(s.size)
puts(s.empty?)
puts(s.delete(4).delete(5).empty?)
end2
false
trueto_a #
Set.to_a(set: Set[T]) -> List[T]The elements in first-insertion order.
def main() -> Void
puts(Set.new([9, 7, 9, 8]).to_a)
end[9, 7, 8]union, intersection and difference #
Set.union(set: Set[T], other: Set[T]) -> Set[T]
Set.intersection(set: Set[T], other: Set[T]) -> Set[T]
Set.difference(set: Set[T], other: Set[T]) -> Set[T]union gives the elements of set, then the elements of other that set lacks. intersection and difference keep the order of set.
def main() -> Void
a = Set.new([1, 2, 3, 4])
b = Set.new([4, 3, 9])
puts(a.union(b))
puts(a.intersection(b))
puts(a.difference(b))
puts(b.difference(a))
endSet[1, 2, 3, 4, 9]
Set[3, 4]
Set[1, 2]
Set[9]subset? #
Set.subset?(set: Set[T], other: Set[T]) -> BoolTrue when every element of set is in other. The empty set is a subset of every set.
def main() -> Void
small = Set.new([2, 3])
big = Set.new([1, 2, 3])
puts(small.subset?(big))
puts(big.subset?(small))
puts(small.subset?(small))
endtrue
false
true