Skip to content

Instantly share code, notes, and snippets.

@mattantonelli
Last active July 19, 2017 18:17
Show Gist options
  • Save mattantonelli/b19d44627eca66f6d7516756c2cc302c to your computer and use it in GitHub Desktop.
Save mattantonelli/b19d44627eca66f6d7516756c2cc302c to your computer and use it in GitHub Desktop.
A sexy version of Hash that strips whitespace from string keys. #StripperHash
class Hash
def strip
StripperHash.new(self)
end
end
class StripperHash < Hash
def initialize(constructor = {})
if constructor.respond_to?(:to_hash)
super
merge!(constructor)
else
super(constructor)
end
end
def []=(key, value)
super(key.strip, value)
end
alias_method :store, :[]=
def merge(other_hash)
super(strip(other_hash))
end
alias_method :update, :merge
def merge!(other_hash)
super(strip(other_hash))
end
def replace(other_hash)
super(strip(other_hash))
end
private
def strip(hash)
stripped_hash = hash.dup
hash.each_key do |key|
if key.is_a?(String) && (stripped_key = key.strip) && key != stripped_key
stripped_hash[stripped_key] = stripped_hash.delete(key)
end
end
stripped_hash
end
end
@mattantonelli
Copy link
Author

>> h = { 'test   ' => 1, test: 2 }
=> {"test   "=>1, :test=>2}

>> sh = h.strip
=> {:test=>2, "test"=>1}

>> sh.class
=> StripperHash

>> sh = StripperHash.new('test   ' => 1, test: 2)
=> {:test=>2, "test"=>1}

>> sh['test2  '] = 3
=> 3

>> sh
=> {:test=>2, "test"=>1, "test2"=>3}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment