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

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

    While Ryan McGeary's approach works great and is almost certainly the correct way to do it, there is a bug that I haven't been able to discern the cause of, which breaks the Hash[] method.

    For example:

    r = CaseInsensitiveHash['ASDF', 1, 'QWER', 2]
    => {"ASDF"=>1, "QWER"=>2}
    r['ASDF']
    => nil
    ap r
    {
        "ASDF" => nil,
        "QWER" => nil
    }
    => {"ASDF"=>1, "QWER"=>2}
    

    Although I've not been able to find or fix the underlying cause of the bug, the following hack does ameliorate the problem:

    r = CaseInsensitiveHash.new(Hash['ASDF', 1, 'QWER', 2])
    => {"asdf"=>1, "qwer"=>2}
    r['ASDF']
    => 1
    ap r
    {
        "asdf" => 1,
        "qwer" => 2
    }
    => {"asdf"=>1, "qwer"=>2}
    

提交回复
热议问题