# Create new Set.
s = Set.new(["plato", "socrates"])
# Add two more elements.
# Get size.
# See if Set includes this element.
Merge, each. Next, this program uses the merge() method and the each() iterator. With merge(), we pass in a collection and the set adds all of its elements.
Detail With each, we iterate over the elements in the set. This uses the same syntax forms available on the hash and array in Ruby.
Tip This is the simplest way to loop over a set. In this example, we use the identifier "n."
# Create set.
s = Set.new(["x", "y"])
# Merge in these two elements.
# Iterate the set.
s.each do |n|
# Display the element.
Subset, operators. One common operation with a set is the "subset" test. We can determine if all elements from one set are contained within another. We can use <= or the "subset?" method.
# Contains three elements.
set1 = Set.new [10, 20, 30]
# Is a superset of set1.
set2 = Set.new [10, 20, 30, 40, 50]
# This is true.
if set1 <= set2
# This is not evaluated to true.
if set2 <= set1
# This is true.# ... Subset is the same as the <= operator.
A summary. A set stores just keys, not values. In this way, it is like a hash with no values. In places where no values are required, this leads to clearer code.
Set benefits. Performance with sets is good—hashed lookups make searches faster. But the greater benefit with a set is its logical methods, which simplify code.