Created
November 14, 2012 02:41
-
-
Save filipebarcos/4069956 to your computer and use it in GitHub Desktop.
symbolize keys for hashes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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