How to assign hash['a']['b']= 'c' if hash['a'] doesn't exist?
问题 Is there any way simpler than if hash.key?('a') hash['a']['b'] = 'c' else hash['a'] = {} hash['a']['b'] = 'c' end 回答1: The easiest way is to construct your Hash with a block argument: hash = Hash.new { |h, k| h[k] = { } } hash['a']['b'] = 1 hash['a']['c'] = 1 hash['b']['c'] = 1 puts hash.inspect # "{"a"=>{"b"=>1, "c"=>1}, "b"=>{"c"=>1}}" This form for new creates a new empty Hash as the default value. You don't want this: hash = Hash.new({ }) as that will use the exact same hash for all