Skip to content

Instantly share code, notes, and snippets.

@shostakovich
Created October 7, 2012 11:36
Show Gist options
  • Save shostakovich/3848037 to your computer and use it in GitHub Desktop.
Save shostakovich/3848037 to your computer and use it in GitHub Desktop.
Set.rb illuminated
# given enumerable object.
def |(enum)
dup.merge(enum)
end
alias + | ##
alias union | ##
# Returns a new set built by duplicating the set, removing every
# element that appears in the given enumerable object.
def -(enum)
dup.subtract(enum)
end
alias difference - ##
# Returns a new set containing elements common to the set and the
# given enumerable object.
def &(enum)
n = self.class.new
do_with_enum(enum) { |o| n.add(o) if include?(o) }
n
end
alias intersection & ##
# Returns a new set containing elements exclusive between the set
# and the given enumerable object. (set ^ enum) is equivalent to
# ((set | enum) - (set & enum)).
def ^(enum)
n = Set.new(enum)
each { |o| if n.include?(o) then n.delete(o) else n.add(o) end }
n
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment