Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

h = {   data: {     user: {       value: "John Doe"      }   } } 

To assign value to the nested hash, we can use

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

However if any part in the middle is missing, it will cause error.

Something like

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

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

To safely assign value, we can do

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

But is there better way to do that?

like image 901
sbs Avatar asked Jan 05 '16 20:01

sbs


1 Answers

It's not without its caveats (and doesn't work if you're receiving the hash from elsewhere), but a common solution is 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" } } } 
like image 132
Jordan Running Avatar answered Oct 15 '22 02:10

Jordan Running