How to assign hash['a']['b']= 'c' if hash['a'] doesn't exist?

后端 未结 5 1169
渐次进展
渐次进展 2020-11-29 04:46

Is there any way simpler than

if hash.key?(\'a\')
  hash[\'a\'][\'b\'] = \'c\' 
else  
  hash[\'a\'] = {}
  hash[\'a\'][\'b\'] = \'c\' 
end
5条回答
  •  半阙折子戏
    2020-11-29 05:23

    If you create hash as the following, with default value of a new (identically default-valued) hash: (thanks to Phrogz for the correction; I had the syntax wrong)

    hash = Hash.new{ |h,k| h[k] = Hash.new(&h.default_proc) }
    

    Then you can do

    hash["a"]["b"] = "c"
    

    without any additional code.

提交回复
热议问题