Skip to Content
Course content
Click on the "Edit" button in the top corner of the screen to edit your slide content.

I see this all the time in code reviews from developers who are new to Ruby: they need a collection of unique items, so they use an Array and simply call .uniq whenever they need to clean it up, or they wrap every single insertion in an unless array.include?(item) block. It feels intuitive because you're already comfortable with Arrays, but it's a performance landmine.

The "Just Use Array#uniq" Trap

Let's look at why that approach fails as your data grows. Imagine you're processing a log file with 100,000 lines to find every unique IP address that visited your site.


# The "Naive" Way
unique_ips = []
log_entries.each do |ip|
  unique_ips << ip unless unique_ips.include?(ip)
end

The problem here is that include? is a linear search. For every single IP in your log, Ruby has to scan the unique_ips array from the beginning until it finds a match or hits the end. If you have 100,000 entries, you're potentially doing billions of comparisons. Your program will crawl to a halt, and you'll be wondering why your CPU is screaming.

Leveraging the Hash-backed Speed of Set

This is exactly why the Set class exists. A Set is essentially a wrapper around a Hash where the elements you add become the keys of the hash, and the values are just ignored. Because Hash lookups are (effectively) instant regardless of the size of the collection, checking for existence or adding a new element happens in constant time.

First, a quick heads-up: Set is part of the standard library, but not the core, so you have to explicitly require it.

require 'set'

unique_ips = Set.new
log_entries.each do |ip|
  unique_ips.add(ip) # No need to check if it exists first!
end

In this version, adding an IP that's already there does nothing, and adding a new one is incredibly fast. I personally use Sets whenever I'm dealing with "membership" logic—basically any time the question is "Is this thing in the group?" rather than "What is the third item in the list?"

Performing Set Mathematics

Beyond just uniqueness, the Set class gives you powerful tools for comparing collections that would be clunky to write with Arrays. These are based on mathematical set theory, and once they click, they make your code much more expressive.

Consider two sets of user IDs: those who have a "Premium" subscription and those who have "Logged In" today.

premium_users = Set[1, 2, 3, 4, 5]
active_users = Set[4, 5, 6, 7, 8]

# Intersection: Who is both premium AND active?
premium_and_active = premium_users & active_users 
# => #<Set: {4, 5}>

# Union: Who is either premium OR active (or both)?
all_relevant_users = premium_users | active_users 
# => #<Set: {1, 2, 3, 4, 5, 6, 7, 8}>

# Difference: Who is premium but HASN'T logged in today?
inactive_premium = premium_users - active_users 
# => #<Set: {1, 2, 3}>

Using &, |, and - is far more readable than nesting select and reject blocks. Just remember that these operations return a new Set, leaving the originals untouched.




📋 Practical Task

Filtering Banned Users from a Mailing List

You are building a system to send a newsletter. You have a Set of all subscribed email addresses and a Set of emails that have been flagged as "banned" or "spam."

Your task:

  1. Create a Set called subscribers containing: "alice@example.com", "bob@example.com", "charlie@example.com", and "dan@example.com".
  2. Create a Set called banned_emails containing: "bob@example.com" and "eve@example.com".
  3. Use a set operation to create a third set, final_mailing_list, which contains only the subscribers who are NOT banned.
  4. Print the final_mailing_list to the console.

Hint: Remember to require 'set' at the top of your script!

Rating
0 0

There are no comments for now.

to be the first to leave a comment.