How to elegantly symbolize_keys for a 'nested' hash

后端 未结 6 2198
無奈伤痛
無奈伤痛 2021-02-06 20:46

Consider the following code:

  hash1 = {\"one\" => 1, \"two\" => 2, \"three\" => 3}
  hash2 = hash1.reduce({}){ |h, (k,v)| h.merge(k => hash1) }
  ha         


        
6条回答
  •  你的背包
    2021-02-06 21:19

    You cannot use this method for params or any other instance of ActionController::Parameters any more, because deep_symbolize_keys method is deprecated in Rails 5.0+ due to security reasons and will be removed in Rails 5.1+ as ActionController::Parameters no longer inherits from Hash

    So this approach by @Uri Agassi seems to be the universal one.

    JSON.parse(JSON[h], symbolize_names: true)
    

    However, Rails Hash object still does have it.

    So options are:

    • if you don't use Rails or just don't care:

      JSON.parse(JSON[h], symbolize_names: true)
      
    • with Rails and ActionController::Parameters:

      params.to_unsafe_h.deep_symbolize_keys
      
    • with Rails and plain Hash

      h.deep_symbolize_keys
      

提交回复
热议问题