Created
April 15, 2012 11:36
-
-
Save tuzz/2392163 to your computer and use it in GitHub Desktop.
Disallow nil from hash and array
This file contains 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
# hash = HashWithoutNilValues.new | |
# hash[:a] = nil | |
# hash # => {} | |
# | |
# hash[:a] = {} | |
# hash[:a].class # => HashWithoutNilValues | |
# | |
# hash[:a] = [] | |
# hash[:a].class # => ArrayWithoutNilValues | |
# | |
# hash[:a] << nil | |
# hash[:a] # => [] | |
# | |
# hash[:a] << {} | |
# hash[:a].first.class # => HashWithoutNilValues | |
# | |
class HashWithoutNilValues < Hash | |
def []=(key, value) | |
return if value.nil? | |
value = HashWithoutNilValues.new if value == {} | |
value = ArrayWithoutNilValues.new if value == [] | |
super(key, value) | |
end | |
end | |
class ArrayWithoutNilValues < Array | |
def <<(value) | |
return if value.nil? | |
value = ArrayWithoutNilValues.new if value == [] | |
value = HashWithoutNilValues.new if value == {} | |
super(value) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment