Skip to content

Instantly share code, notes, and snippets.

@sporkmonger
Created December 9, 2008 17:43
Show Gist options
  • Save sporkmonger/33999 to your computer and use it in GitHub Desktop.
Save sporkmonger/33999 to your computer and use it in GitHub Desktop.
CaseInsensitiveHash
##
# This Hash subclass stores keys in a case-insensitive manner.
class CaseInsensitiveHash < Hash
##
# @see Hash#[]
def [](key)
return super(key.downcase)
end
##
# @see Hash#[]=
def []=(key, value)
@key_labels ||= {}
@key_labels[key.downcase] = key
return super(key.downcase, value)
end
##
# @see Hash#store
alias_method :store, :[]=
##
# @see Hash#include?
def include?(key)
return super(key.downcase)
end
##
# Returns the labels for the keys, exactly as they were originally
# entered.
#
# @return [Array] The key labels.
def key_labels
@key_labels ||= {}
self.keys.map { |key| @key_labels[key] }
end
##
# Converts to a normal Hash object. The key labels are used as the
# Hash keys.
#
# @return [Hash] The converted Hash.
def to_hash
# Iterate over key labels, and look up the value, stuffing everything
# into a new Hash as we go.
self.key_labels.inject({}) do |accu, label|
accu[label] = self[label]
accu
end
end
##
# @see Hash#to_s
def to_s
return self.to_hash.to_s
end
##
# @see Hash#inspect
def inspect
return self.to_hash.inspect
end
end
>> hash = CaseInsensitiveHash.new
=> {}
>> hash["ETag"] = "asdf"
=> "asdf"
>> hash["X-Originating-IP"] = "localhost"
=> "localhost"
>> hash["Content-MD5"] = "asdf"
=> "asdf"
>> hash
=> {"X-Originating-IP"=>"localhost", "ETag"=>"asdf", "Content-MD5"=>"asdf"}
>> hash.include?("ETag")
=> true
>> hash.include?("etag")
=> true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment