How do I use the fetch method for nested hash?

后端 未结 7 1423
后悔当初
后悔当初 2021-02-19 14:45

I have the following hash:

hash = {\'name\' => { \'Mike\' => { \'age\' => 10, \'gender\' => \'m\' } } }

I can access the age by:

7条回答
  •  夕颜
    夕颜 (楼主)
    2021-02-19 15:27

    If your goal is to raise a KeyError when any of the intermediate keys are missing, then you need to write your own method. If instead you're using fetch to provide default values for missing keys, then you can circumvent the use of fetch by constructing the Hashes with a default values.

    hash = Hash.new { |h1, k1| h1[k1] = Hash.new { |h2, k2| h2[k2] = Hash.new { |h3, k3| } } }
    hash['name']['Mike']
    # {}
    hash['name']['Steve']['age'] = 20
    hash
    # {"name"=>{"Mike"=>{}, "Steve"=>{"age"=>20}}}
    

    This won't work for arbitrarily nested Hashes, you need to choose the maximum depth when you construct them.

提交回复
热议问题