json - How to set a default value for hashtable in ruby? -


is there anyway set hashtable's default value in ruby after filling hashtable json.parse() in ruby?

you can set hash's default value method hash#default_proc.

for example, suppose:

h = { :a=>1, :b=>2 } 

and if h not have key k want h[k] return empty array. so:

h.default_proc = ->(h,k) { [] } # write h.default_proc = ->(*) { [] }  h[:a] #=> 1 h[:b] #=> 2 h[:c] #=> [] h #=> { :a=>1, :b=>2 } # h unchanged 

if want add key , value hash:

h.default_proc = ->(h,k) { h[k] = [] }  h[:a] #=> 1 h[:b] #=> 2 h[:c] #=> [] h #=> {:a=>1, :b=>2, :c=>[]}  

Comments

Popular posts from this blog

matlab - error with cyclic autocorrelation function -

django - (fields.E300) Field defines a relation with model 'AbstractEmailUser' which is either not installed, or is abstract -

c# - What is a good .Net RefEdit control to use with ExcelDna? -