DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Recursively Symbolize Keys Supports Hash And Array

04.21.2010
| 7145 views |
  • submit to reddit
        Recursively Symbolize Keys supports Hash and Array

def symbolize_keys(obj)
  case obj
  when Array
    obj.inject([]){|res, val|
      res << case val
      when Hash, Array
        symbolize_keys(val)
      else
        val
      end
      res
    }
  when Hash
    obj.inject({}){|res, (key, val)|
      nkey = case key
      when String
        key.to_sym
      else
        key
      end
      nval = case val
      when Hash, Array
        symbolize_keys(val)
      else
        val
      end
      res[nkey] = nval
      res
    }
  else
    obj
  end
end
    

Comments

Alexey Tarasevich replied on Wed, 2010/01/06 - 7:52pm

Hi, kabaken! I think map here would be more appropriate: def symbolize_keys arg case arg when Array arg.map { |elem| symbolize_keys elem } when Hash Hash[ arg.map { |key, value| k = key.is_a?(String) ? key.to_sym : key v = symbolize_keys value [k,v] }] else arg end end

Snippets Manager replied on Wed, 2010/04/21 - 1:39pm

Hi,xetas! Cool. Thats better. Thanx :-)