Home > Articles > Programming > Ruby

  • Print
  • + Share This
This chapter is from the book

This chapter is from the book

Eliminating Duplicate Data from Arrays (Sets)

You can approach this problem in two different ways. If you are adding all your data to your Array up front, you can use the expensive way, #uniq, above, because you have to do it only once.

But if you will constantly be adding and removing data to your collection and you need to know that all the data is unique at any time, you need something more to guarantee that all your data is unique, but without a lot of cost. A set does just that.

Sets are a wonderful tool: They ensure that the values you have stored are unique. This is accomplished by using a Hash for its storage mechanism, which, in turn, generates a unique signifier for any keys it’s storing. This guarantees that you won’t have the same data in the set while also keeping things accessible and fast! Beware, however, sets are not ordered.

require 'set'
myset = Set::new [1, 1, 2, 3, 4, 4]
    #=> #<Set: {1, 2, 3, 4}>

Adding duplicate data causes no change:

myset.add 4
    #=> #<Set: {1, 2, 3, 4}>
  • + Share This
  • 🔖 Save To Your Account