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

后端 未结 4 1022
执笔经年
执笔经年 2020-12-30 01:55
h = {
  data: {
    user: {
      value: \"John Doe\" 
    }
  }
}

To assign value to the nested hash, we can use

h[:data][:user][:         


        
4条回答
  •  [愿得一人]
    2020-12-30 02:34

    I found a simple solution to set the value of a nested hash, even if a parent key is missing, even if the hash already exists. Given:

    x = { gojira: { guitar: { joe: 'charvel' } } }
    

    Suppose you wanted to include mario's drum to result in:

    x = { gojira: { guitar: { joe: 'charvel' }, drum: { mario: 'tama' } } }
    

    I ended up monkey-patching Hash:

    class Hash
    
        # ensures nested hash from keys, and sets final key to value
        # keys: Array of Symbol|String
        # value: any
        def nested_set(keys, value)
          raise "DEBUG: nested_set keys must be an Array" unless keys.is_a?(Array)
    
          final_key = keys.pop
          return unless valid_key?(final_key)
          position = self
          for key in keys
            return unless valid_key?(key)
            position[key] = {} unless position[key].is_a?(Hash)
            position = position[key]
          end
          position[final_key] = value
        end
    
        private
    
          # returns true if key is valid
          def valid_key?(key)
            return true if key.is_a?(Symbol) || key.is_a?(String)
            raise "DEBUG: nested_set invalid key: #{key} (#{key.class})"
          end
    end
    

    usage:

    x.nested_set([:instrument, :drum, :mario], 'tama')
    

    usage for your example:

    h.nested_set([:data, :user, :value], 'Bob')
    

    any caveats i missed? any better way to write the code without sacrificing readability?

提交回复
热议问题