Introduction

Welcome to our Ruby Sets lesson! In Ruby, sets are collections that store unique elements, similar to arrays but without duplicates. Sets are part of the Set class, which offers a variety of methods to manage unique collections efficiently. Throughout this lesson, you'll learn how to create and manipulate sets in Ruby, perform set operations, and understand the performance benefits they provide. Let’s dive in!

Creating and Manipulating Sets

To work with sets in Ruby, you’ll need to require the set library. You can create a set using the Set.new method.

When you create a set using Set.new, duplicates in the input array are automatically removed because sets enforce uniqueness. Sets use a hash-based structure under the hood, where each element’s value is hashed. This ensures that duplicates are identified and ignored during initialization.

require 'set'

# Creating a set with unique elements
my_set = Set.new([1, 2, 3, 4, 5, 5, 5])
puts my_set.inspect  # Output: #<Set: {1, 2, 3, 4, 5}>

# Adding an element to the set
my_set.add(6)
puts my_set.include?(1)  # Output: true

# Removing an element
my_set.delete(1)
puts my_set.include?(1)  # Output: false

# Trying to remove a non-existent element
my_set.delete(7)  # No error, just no change if element doesn't exist

Ruby’s Set provides methods like add, include?, and delete, making it straightforward to manage collections of unique items.

Set Operations

Ruby’s Set class supports powerful operations that allow you to combine, intersect, or find the difference between sets, making it ideal for handling unique collections.

require 'set'

set_1 = Set.new([1, 2, 3, 4])
set_2 = Set.new([3, 4, 5, 6])

# Union of two sets
puts (set_1 | set_2).inspect  # Output: #<Set: {1, 2, 3, 4, 5, 6}>

# Intersection of two sets
puts (set_1 & set_2).inspect  # Output: #<Set: {3, 4}>

# Difference of two sets
puts (set_1 - set_2).inspect  # Output: #<Set: {1, 2}>

# Symmetric difference of two sets
puts (set_1 ^ set_2).inspect  # Output: #<Set: {1, 2, 5, 6}>
  • Union (|): Combines elements from both sets, excluding duplicates.
  • Intersection (&): Finds only the elements common to both sets.
  • Difference (-): Returns elements present in the first set but not in the second set.
  • Symmetric Difference (^): Returns elements in either set, but not in both (exclusive OR).

These operations provide a simple and efficient way to work with unique collections.

Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal