Did you know? DZone has great portals for Python, Cloud, NoSQL, and HTML5!
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 5886 posts at DZone. View Full User Profile

Convert Hash Key Strings To Symbols If They Look Like Them.

11.04.2008
Email
Views: 4937
  • submit to reddit
        Ever read in a YAML file that has symbols in it, but the symbols end up as Strings (eg: ":foo" instead of :foo)?  Here's your solution.  Hash#key_strings_to_symbols!

class Hash
  # Recursively replace key names that should be symbols with symbols.
  def key_strings_to_symbols!
    r = Hash.new
    self.each_pair do |k,v|
      if ((k.kind_of? String) and k =~ /^:/)
        v.key_strings_to_symbols! if v.kind_of? Hash and v.respond_to? :key_strings_to_symbols!
        r[k.slice(1..-1).to_sym] = v
      else
        v.key_strings_to_symbols! if v.kind_of? Hash and v.respond_to? :key_strings_to_symbols!
        r[k] = v
      end
    end
    self.replace(r)
  end
end