How to Convert a Ruby Array to Set?

In Ruby, you can convert an array to a set by using the Enumerable#to_set method, for example, like so:

array = [1, 2, 2, 2, 3, 4, 5]
set = array.to_set

print set #=> <Set: {1, 2, 3, 4, 5}>
print set.class #=> Set

As you can see from the example above, the array is converted to a set object, and all non-unique values are removed from the resulting set.


This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.