DEV Community

Cover image for Ruby Sets
Shaher Shamroukh
Shaher Shamroukh

Posted on

Ruby Sets

What is a Ruby Set

Ruby Set is a class implementing the mathematical concept of Set.
Meaning it stores items like an array without duplicate items so all the items in a set are guaranteed to be unique and it is a lot more faster and has some special capabilities.

Before getting into how to use set class let's first determine when do we use it.

When to use sets

Here are the few cases where sets work better:-
1- Elements order does not matter.
2- No duplicate values allowed.
3- The sequences needs to be compared for equality regardless of the order.

How to use sets

>> require 'set'
>> fruits = Set.new
>> fruits << "Apple"
>> fruits.add("Orange")
>> fruits
=> #<Set: {"Apple", "Orange"}>
Enter fullscreen mode Exit fullscreen mode

We can also do this

>> numbers = Set[1, 2, 3, 4]
=> #<Set: {1, 2, 3, 4}>
Notice no duplicates allowed:
>> numbers << 3
=> #<Set: {1, 2, 3, 4}>
Enter fullscreen mode Exit fullscreen mode

Here are some useful methods to use with sets

#include?
>> numbers.include?(4)
=> true

#delete
>> numbers.delete(2)
=> #<Set: {1, 3, 4}>

#disjoint?
>> numbers
=> #<Set: {1, 3, 4}>
>> numbers.disjoint? Set[5, 6]
=> true      #No elements in common the opposite is intersect?

#union or |
>> numbers
=> #<Set: {1, 3, 4}>
>> numbers.union Set[2, 4, 5] 
=> #<Set: {1, 3, 4, 2, 5}>
>> numbers | Set[2, 4, 5] 
=> #<Set: {1, 3, 4, 2, 5}>

#delete_if & It's opposite keep_if
>> fruits
=> #<Set: {"Apple", "Orange", "melon"}>
>> fruits.delete_if { |f| f == "melon"}
=> #<Set: {"Apple", "Orange"}>

#clear
>> numbers.clear
=> #<Set: {}>
Enter fullscreen mode Exit fullscreen mode

As well as the method above Set is easy to use with Enumerable objects.

For more details please check out ruby-doc

Now we know how to use ruby sets for better performance and easier coding.
So if you are using Ruby in your current project and you think that any of the cases above apply to you, you should consider using ruby sets.

I hope you enjoyed reading the article as i enjoyed writing it if so Please share it so more people can find it 🙂

Top comments (0)