easierbycode
9/11/2012 - 6:24 PM

## Set operations

Set operations

``````# Subsets and Supersets
Set[1,2,3].subset?(Set[1,2,3,4])
#=> true

Set[1,2,3].superset(Set[3,6,9])
#=> false

Set[1,2,3].proper_subset?(Set[1,2,3])
#=> false``````
``````# Partitioning using divide
Set[1,2,3,4,5,6,7,8,9].divide {|el| el%3 }
#=> #{ #{1,4,7},
#      #{2,5,8},
#      #{3,6,9}
#      }

We can use divide to partition a group of text strings by starting character
z = Set["alpha", "bravo", "charlie", "delta", "echo", "apple", "code"]

z.divide {|str| str[0]}
#=>  { {"alpha", "apple"},
#      {"bravo"},
#      {"charlie", "code"},
#      {"delta"},
#      {"echo"}
#     }``````
``````# Enumerable methods work on Sets
Set[2,4,8,16].each {|el| puts el}
#=> 2
#   4
#   8
#   16

# Enumerable methods that don't make sense in terms of a Set return an Array
Set[3,2,5,1].sort
#=> [1,2,3,5]``````
``````require 'set'

# Union
Set[1,2,3] | Set[3,4,5]
#=> #{1,2,3,4,5}

# Intersection
Set[1,2,3] & Set[2,3,4,5]
#=> #{2,3}

# Subtraction
Set[1,2,3,4] - Set[3,4,5]
#=> #{1,2}

# Set equality is based only on contents, not content and position like an Array
Set[1,2,3] == Set[3,1,2]
#=> true``````