How to Convert a Ruby Array to Set?

Convert 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.


Hope you found this post useful. It was published . Please show your love and support by sharing this post.