Sets
Anonymous contributor
Anonymous contributor3071 total contributions
Anonymous contributor
Published Jul 30, 2021Updated May 15, 2024
Contribute to Docs
In Ruby, a Set
is a collection of unordered, non-duplicated values. They are functional like an Array
but have quick lookup with Hash
-storage.
Syntax
In order to use Sets:
- Import the
set
module withrequire()
- Use the
Set
keyword followed by brackets ([]
) containing comma-separated values
require("set")test_set = Set[1, 2]puts test_set # Output: #<Set: {1, 2}>
Example
Values can be added to Sets with #add()
:
test_set.add("It's a Beautiful Day!")puts test_set
They can also be deleted with #delete()
. Pass in the actual value. If the value doesn’t exist in the Set, nothing happens to it:
test_set.delete(2)puts test_set # Output: #<Set: {1, "It's a Beautiful Day!"}>test_set.delete(100)puts test_set # Output: #<Set: {1, "It's a Beautiful Day!"}>
Since Sets are array- and hash-like, they are iterable and can use methods like each
:
require("set")test_set = Set[1, 2]test_set.add(3)test_set.add("It's a Beautiful Day!")test_set.each do |element|puts elementend
All contributors
- Anonymous contributorAnonymous contributor3071 total contributions
- BrandonDusch580 total contributions
- THE-Spellchecker154 total contributions
- christian.dinh2476 total contributions
- Anonymous contributor
- BrandonDusch
- THE-Spellchecker
- christian.dinh
Looking to contribute?
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.