Ruby: Set class

Set Base

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}

# ignore order
Set[1,2,3] == Set[3,1,2] #=> true

Check Subset Superset

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

Set[1,2,3].subset?(Set[1,2,3]) #=> true

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

Set[1,2,3].proper_subset?(Set[1,2,3]) #=> false

Set Divide Subset

Set[1,2,3,4,5,6,7,8,9].divide {|el| el%3 }
#=> #<Set: {#<Set: {1, 4, 7}>, #<Set: {2, 5, 8}>, #<Set: {3, 6, 9}>}>

# group subset

z = Set["alpha", "bravo", "charlie", "delta", "echo", "apple", "code"]

z.divide {|str| str[0]}
=> #<Set: {#<Set: {"alpha", "apple"}>, #<Set: {"bravo"}>, #<Set: {"charlie", "code"}>, #<Set: {"delta"}>, #<Set: {"echo"}>}>

Set Enumerable

Set[2,4,8,16].each {|el| p el}

Set[3,2,5,1].sort #=> [1,2,3,5]

Set or Array

Set Class doc When Is a Set Better Than an Array in Ruby?