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

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

    Any reason for not just using string#upcase?

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

    If you insist on modifying hash, you can do something like the following

    class Hash
    alias :oldIndexer :[]
    
    def [](val)
       if val.respond_to? :upcase then oldIndexer(val.upcase) else oldIndexer(val) end
    end
    end
    

    Since it was brought up, you can also do this to make setting case insensitive:

    class Hash
    alias :oldSetter :[]=
    def []=(key, value)
        if key.respond_to? :upcase then oldSetter(key.upcase, value) else oldSetter(key, value) end
    end
    end
    

    I also recommend doing this using module_eval.

提交回复
热议问题