How to elegantly symbolize_keys for a 'nested' hash

后端 未结 6 2183
無奈伤痛
無奈伤痛 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:18

    In rails you can create HashWithIndifferentAccess class. Create an instance of this class passing your hash to its constructor and then access it with keys that are symbols or strings (like params of Controller's Actions):

    hash = {'a' => {'b' => [{c: 3}]}}
    
    hash = hash.with_indifferent_access
    # equal to:
    # hash = ActiveSupport::HashWithIndifferentAccess.new(hash)
    
    hash[:a][:b][0][:c]
    
    => 3
    

提交回复
热议问题