Skip to content

Instantly share code, notes, and snippets.

@filipebarcos
Created November 14, 2012 02:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save filipebarcos/4069956 to your computer and use it in GitHub Desktop.
Save filipebarcos/4069956 to your computer and use it in GitHub Desktop.
symbolize keys for hashes
class Hash
def symbolize_keys
self.inject({}) { |acc, elem| acc.merge!(elem[0].to_sym => elem[1]) }
end
def deep_symbolize_keys
self.inject({}) do |acc, elem|
acc.merge! elem[0].to_sym => elem[1].class == Hash ? elem[1].deep_symbolize_keys : elem[1]
end
end
end
hash = {"a" => {"b" => 1}}
p hash.deep_symbolize_keys
# {:a => {:b => 1}}
p hash.symbolize_keys
# {:a => {"b" => 1}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment