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

前端 未结 6 1348
無奈伤痛
無奈伤痛 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:25

    To prevent this change from completely breaking independent parts of your program (such as other ruby gems you are using), make a separate class for your insensitive hash.

    class HashClod < Hash
      def [](key)
        super _insensitive(key)
      end
    
      def []=(key, value)
        super _insensitive(key), value
      end
    
      # Keeping it DRY.
      protected
    
      def _insensitive(key)
        key.respond_to?(:upcase) ? key.upcase : key
      end
    end
    
    you_insensitive = HashClod.new
    
    you_insensitive['clod'] = 1
    puts you_insensitive['cLoD']  # => 1
    
    you_insensitive['CLod'] = 5
    puts you_insensitive['clod']  # => 5
    

    After overriding the assignment and retrieval functions, it's pretty much cake. Creating a full replacement for Hash would require being more meticulous about handling the aliases and other functions (for example, #has_key? and #store) needed for a complete implementation. The pattern above can easily be extended to all these related methods.

提交回复
热议问题