Ruby Sets - Intermediate


Sets implement a collection of unordered unique values. They combine the Array's intuitive inter-operation facilities with the speed of Hash's lookup. Unlike the previous data structures we have worked with, sets are not part of Ruby's core library. As such, we need to include them in order to make use of their functionality. To do this we must add a require statement at the top of our file: require 'set'.

>> require 'set'
true
# set is part of the standard library and must be brought in by a 'require' statement
>> (1..10).to_set
[
    [0] 1,
    [1] 2,
    [2] 3,
    [3] 4,
    [4] 5,
    [5] 6,
    [6] 7,
    [7] 8,
    [8] 9,
    [9] 10
]

Now that we have a set, what can we do with it? Let's start by adding some items:

>> set.add(11)
[
    [ 0] 1,
    [ 1] 2,
    [ 2] 3,
    [ 3] 4,
    [ 4] 5,
    [ 5] 6,
    [ 6] 7,
    [ 7] 8,
    [ 8] 9,
    [ 9] 10,
    [10] 11
]
# notice we used 'add' with a set instead of 'push' as we would with an array

# we can still use the << append operation with sets

>> set << 12
[
    [ 0] 1,
    [ 1] 2,
    [ 2] 3,
    [ 3] 4,
    [ 4] 5,
    [ 5] 6,
    [ 6] 7,
    [ 7] 8,
    [ 8] 9,
    [ 9] 10,
    [10] 11,
    [11] 12
]

# one benefit of using a set is that it requires all items be unique
# this ensures no duplicates in your collection
>> set << 12
[
    [ 0] 1,
    [ 1] 2,
    [ 2] 3,
    [ 3] 4,
    [ 4] 5,
    [ 5] 6,
    [ 6] 7,
    [ 7] 8,
    [ 8] 9,
    [ 9] 10,
    [10] 11,
    [11] 12
]

Notice that set did not throw an error or add another item. It only returned the set to us without performing any additional operations.

Sets are stored in memory as a Hash, which provides some performance benefits. Sets will come in handy when you are comparing different collections, allowing you to quickly check for similarities and differences between them.

Summary

In this chapter we explored Ruby's 'set', a unique hybrid that acts as a combination of both the array and hash. We determined the set acts like an array but only stores unique values. It functions like a hash internally, providing an increase in performance.

results matching ""

    No results matching ""