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
Post a Comment