Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created November 26, 2013 00:59
Show Gist options
  • Save jgaskins/7651714 to your computer and use it in GitHub Desktop.
Save jgaskins/7651714 to your computer and use it in GitHub Desktop.
A Set class that rejects nil
require 'set'
class NoNilSet
include Enumerable
def initialize(values=[])
@set = Set.new
@set += Array(values).compact
end
def +(other)
self.class.new(@set + other.compact)
end
def <<(value)
@set << value unless value.nil?
self
end
def compact
self
end
def each(&block)
@set.each(&block)
end
end
s = NoNilSet.new [1, 2, :foo, nil, false]
t = NoNilSet.new [1, :bar]
s += t
s << nil
s += [nil]
p s
# => #<NoNilSet:0x007fbf22142330 @set=#<Set: {1, 2, :foo, false, :bar}>>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment