DEV Community

Cover image for Set Class in Ruby đź’Ž
Margarita Potylitsyna
Margarita Potylitsyna

Posted on

Set Class in Ruby đź’Ž

In Ruby, the Set class is a collection of unordered, unique values—kind of like an array, but with no duplicates allowed. It maintains unique elements only. Supports set operations: union, intersection, difference, etc.

How to use:

require "set"

s = Set.new([1, 2, 3])
s.add(3)      # duplicate, won't be added
s.add(4)
puts s.inspect  # => #<Set: {1, 2, 3, 4}>
Enter fullscreen mode Exit fullscreen mode

Set Operations:

a = Set.new([1, 2, 3])
b = Set.new([3, 4, 5])

puts a | b     # Union => #<Set: {1, 2, 3, 4, 5}>
puts a & b     # Intersection => #<Set: {3}>
puts a - b     # Difference => #<Set: {1, 2}>
Enter fullscreen mode Exit fullscreen mode

Conversion:

arr = [1, 2, 2, 3]
unique_set = Set.new(arr)
puts unique_set.to_a  # => [1, 2, 3]
Enter fullscreen mode Exit fullscreen mode

When to Use Set:

  • When you need to automatically eliminate duplicates.
  • When performing set-theoretic operations (like unions or intersections).
  • For efficient membership checks (similar to using a hash).

Top comments (0)