How do I create a hash in Ruby that compares strings, ignoring case?

前端 未结 6 1335
無奈伤痛
無奈伤痛 2020-12-09 16:34

In Ruby, I want to store some stuff in a Hash, but I don\'t want it to be case-sensitive. So for example:

h = Hash.new
h[\"HELLO\"] = 7
puts h[\"hello\"]
         


        
6条回答
  •  执念已碎
    2020-12-09 17:33

    If you really want to ignore case in both directions and handle all Hash methods like #has_key?, #fetch, #values_at, #delete, etc. , you'll need to do a little work if you want to build this from scratch, but if you create a new class that extends from class ActiveSupport::HashWithIndifferentAccess, you should be able to do it pretty easily like so:

    require "active_support/hash_with_indifferent_access"
    
    class CaseInsensitiveHash < HashWithIndifferentAccess
      # This method shouldn't need an override, but my tests say otherwise.
      def [](key)
        super convert_key(key)
      end
    
      protected
    
      def convert_key(key)
        key.respond_to?(:downcase) ? key.downcase : key
      end  
    end
    

    Here's some example behavior:

    h = CaseInsensitiveHash.new
    h["HELLO"] = 7
    h.fetch("HELLO")                # => 7
    h.fetch("hello")                # => 7
    h["HELLO"]                      # => 7
    h["hello"]                      # => 7
    h.has_key?("hello")             # => true
    h.values_at("hello", "HELLO")   # => [7, 7]
    h.delete("hello")               # => 7
    h["HELLO"]                      # => nil
    

提交回复
热议问题