Skip to content

Instantly share code, notes, and snippets.

@scottaj
Created August 16, 2012 19:42
Show Gist options
  • Save scottaj/3372980 to your computer and use it in GitHub Desktop.
Save scottaj/3372980 to your computer and use it in GitHub Desktop.
Set operations
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
# 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]
# 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"}
# }
# 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment