ruby - Safely assign value to nested hash using Hash#dig or Lonely operator(&.) -


h = {   data: {     user: {       value: "john doe"      }   } } 

to assign value nested hash, can use

h[:data][:user][:value] = "bob" 

however if part in middle missing, cause error.

something

h.dig(:data, :user, :value) = "bob" 

won't work, since there's no hash#dig= available yet.

to safely assign value, can do

h.dig(:data, :user)&.[]=(:value, "bob")    # or equivalently h.dig(:data, :user)&.store(:value, "bob") 

but there better way that?

it's not without caveats (and doesn't work if you're receiving hash elsewhere), common solution this:

hash = hash.new {|h,k| h[k] = h.class.new(&h.default_proc) }  hash[:data][:user][:value] = "bob" p hash # => { :data => { :user => { :value => "bob" } } } 

Comments

Popular posts from this blog

how to insert data php javascript mysql with multiple array session 2 -

multithreading - Exception in Application constructor -

windows - CertCreateCertificateContext returns CRYPT_E_ASN1_BADTAG / 8009310b -