Why is a string key for a hash frozen?

前端 未结 4 1519
猫巷女王i
猫巷女王i 2021-02-07 00:52

According to the specification, strings that are used as a key to a hash are duplicated and frozen. Other mutable objects do not seem to have such special consideration. For exa

4条回答
  •  滥情空心
    2021-02-07 01:21

    You are askin 2 different questions: theoretical and practical. Lain was the first to answer, but I would like to provide what I consider a proper, lazier solution to your practical question:

    Hash.new { |hsh, key| # this block get's called only if a key is absent
      downcased = key.to_s.downcase
      unless downcased == key # if downcasing makes a difference
        hsh[key] = hsh[downcased] if hsh.has_key? downcased # define a new hash pair
      end # (otherways just return nil)
    }
    

    The block used with Hash.new constructor is only invoked for those missing keys, that are actually requested. The above solution also accepts symbols.

提交回复
热议问题