Learning Ruby [sets]

Sets are a special type of collection that contain elements with unique content. A set can contain any type of object. However, it makes sure that there is only one version of each object in a given set. Sets are created using the Set.new(item) method. This method accepts a collection as an argument. It also supports the definition of a code block to process the contents from the collection being passed as an argument.

A new element can be added to a set using the << operator, or the add(item) and add?(item) methods. These approaches are identical for the most part. Except that add? returns nil if the item already exists in the set. The merge(collection) method enables merging new collections into the set; using the add methods adds an entire collection as a single item.

As expected, the delete(item) method deletes objects from a set.

Using the operators +, -, |, & you can check the union (add), difference (subtract), intersection (and and or) between different set objects. You can also use the superset?(set) and subset?(set) methods to compare two sets to determine if they relate to one another in either of these ways.

Leave a Reply