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

The easiest way is to construct your Hash with a block argument: hash = Hash.new { |h, k| h[k] = { } } hash[‘a’][‘b’] = 1 hash[‘a’][‘c’] = 1 hash[‘b’][‘c’] = 1 puts hash.inspect # “{“a”=>{“b”=>1, “c”=>1}, “b”=>{“c”=>1}}” This form for new creates a new empty Hash as the default value. You don’t want this: … Read more

How to avoid NoMethodError for missing elements in nested hashes, without repeated nil checks?

Ruby 2.3.0 introduced a new method called dig on both Hash and Array that solves this problem entirely. name = params.dig(:company, :owner, :name) It returns nil if the key is missing at any level. If you are using a version of Ruby older than 2.3, you can use the ruby_dig gem or implement it yourself: … Read more