Created
November 26, 2013 00:59
-
-
Save jgaskins/7651714 to your computer and use it in GitHub Desktop.
A Set class that rejects nil
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' | |
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