Created
December 14, 2012 15:47
-
-
Save bogdanRada/4286379 to your computer and use it in GitHub Desktop.
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
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 |
Hello. That is expected. That is how a string gets converted to a symbol. What you are looking for is key.underscore.to_sym
. Feel free to update the code for your own needs. You need activesupport
gem for that though
@softbrada Thank you for this. I use your code as core extension of the Hash class. This way I avoid to use larger Rails gems.
class Hash
def symbolize_keys
case self
when Array
self.inject([]){|res, val|
res << case val
when Hash, Array
symbolize_keys(val)
else
val
end
res
}
when Hash
self.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
self
end
end
end
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hello buddy there is an error when i try to convert string like
"Content-Type"
to symbol it converts to:"Content-Type"