Created
August 16, 2012 19:42
-
-
Save scottaj/3372980 to your computer and use it in GitHub Desktop.
Set operations
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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"} | |
# } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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