This blog is part of our Ruby 2.4 series.
In Ruby, we commonly use
uniq method on an array
to fetch the collection of all unique elements.
But there may be cases
where we might need
elements in a hash
by virtue of uniqueness of its values.
Let’s consider an example of countries that have hosted the Olympics. We only want to know when was the first time a country hosted it.
One way to achieve this is to have a collection of unique country names and then check if that value is already taken while building the result.
As we can see,
the above code requires constructing
an additional array
In processing larger data, loading an array of considerably big size in memory and then carrying out further processing on it, may result in performance and memory issues.
In Ruby 2.4,
Enumerable class introduces
that collects unique
elements while iterating over
the enumerable object.
The usage is similar to that of
Uniqueness can be determined
by the elements themselves
or by a value yielded by the block
passed to the
Similar method is also implemented
Hence we can now call
uniq on lazy enumerables.