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

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

    require 'test/unit'
    class TestCaseIndifferentHash < Test::Unit::TestCase
      def test_that_the_hash_matches_keys_case_indifferent
        def (hsh = {}).[](key) super(key.upcase) end
    
        hsh['HELLO'] = 7
        assert_equal 7, hsh['hello']
      end
    end
    

提交回复
热议问题