Sets in Ruby are unordered collections of unique elements. They provide a powerful way to store and manipulate data without duplicates. Sets are particularly useful when you need to perform set operations like union, intersection, or difference.
To use Sets in Ruby, you first need to require the 'set' library. Here's how you can create a Set:
require 'set'
fruits = Set.new(['apple', 'banana', 'orange'])
numbers = Set[1, 2, 3, 4, 5]
Notice how Sets can be created using either the Set.new
method or the shorthand Set[]
syntax.
Sets provide methods to add and remove elements:
colors = Set.new(['red', 'blue'])
colors.add('green')
colors.delete('blue')
puts colors # Output: #
Ruby Sets support various set operations, making them ideal for mathematical and logical operations:
|
or union
&
or intersection
-
or difference
subset?
superset?
Here's an example demonstrating these operations:
set1 = Set[1, 2, 3, 4]
set2 = Set[3, 4, 5, 6]
puts set1 | set2 # Union: #
puts set1 & set2 # Intersection: #
puts set1 - set2 # Difference: #
puts set1.subset?(Set[1, 2, 3, 4, 5]) # true
You can iterate over a Set using the Ruby Each Iterator:
colors = Set['red', 'green', 'blue']
colors.each { |color| puts color }
Sets in Ruby come with several useful methods:
clear
: Removes all elements from the setempty?
: Checks if the set is emptysize
or length
: Returns the number of elementsinclude?
: Checks if an element exists in the setSets in Ruby are implemented using Hash tables, which provide O(1) average time complexity for add, delete, and lookup operations. This makes Sets particularly efficient for large collections where uniqueness is required.
By mastering Ruby Sets, you'll have a powerful tool for handling unique collections and performing set operations efficiently in your Ruby programs.