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

后端 未结 4 970
执笔经年
执笔经年 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:38

    And building on @rellampec's answer, ones that does not throw errors:

    def dig_set(obj, keys, value)
      key = keys.first
      if keys.length == 1
        obj[key] = value
      else
        obj[key] = {} unless obj[key]
        dig_set(obj[key], keys.slice(1..-1), value)
      end
    end
    
    obj = {d: 'hey'}
    dig_set(obj, [:a, :b, :c], 'val')
    obj #=> {d: 'hey', a: {b: {c: 'val'}}} 
    

提交回复
热议问题