Ad space (banner)
๐Ÿ’ŽRuby Lessons
Lesson 61 / 68

Set Operations with Set (Union, Intersection, Difference)

In this lesson you will learn set operations with Ruby's Set class. This is for anyone searching for "Ruby set operations how to use".

Ruby's Set class supports | (union), & (intersection), and - (difference) as plain operators. The code reads almost exactly like the mathematics.

The sample code computes the union with a | b, the intersection with a & b, and the difference with a - b, converting each to an array and sorting with .to_a.sort before printing. Notice that each of the three operations has its own operator.

A common stumbling block for beginners is choosing between Set and Array. Use a Set when you want set operations and an Array when order or duplicates matter - keeping that in mind helps you pick the right structure.

It is a useful way of thinking for real data work, such as finding the users common to two groups, and the ideas behind intersection and difference also carry over to understanding join operations in SQL.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run Ruby directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)