Created
December 9, 2008 17:43
-
-
Save sporkmonger/33999 to your computer and use it in GitHub Desktop.
CaseInsensitiveHash
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
## | |
# 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 |
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
>> 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