- Slicing an Array
- Iterating over an Array
- Creating Enumerable Classes
- Sorting an Array
- Iterating over Nested Arrays
- Modifying All the Values in an Array
- Sorting Nested Arrays
- Building a Hash from a Config File
- Sorting a Hash by Key or Value
- Eliminating Duplicate Data from Arrays (Sets)
- Working with Nested Sets
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}>