Skip to content

Instantly share code, notes, and snippets.

@gregohardy
Created September 27, 2018 11:00
Show Gist options
  • Save gregohardy/88e5a3b33fe220c12488890ddb529226 to your computer and use it in GitHub Desktop.
Save gregohardy/88e5a3b33fe220c12488890ddb529226 to your computer and use it in GitHub Desktop.
Symbolize a nested hash containing arrays.
def symbolize(obj)
return obj.reduce({}) do |memo, (k, v)|
memo.tap { |m| m[k.to_sym] = symbolize(v) }
end if obj.is_a? Hash
return obj.reduce([]) do |memo, v|
memo << symbolize(v); memo
end if obj.is_a? Array
obj
end
test = {
:item => 1,
:stuff => 2,
:h => { 'a' => 2, 'b' => "string" },
'array' => [ {'c' => 4}, { :d => "major string with description"}],
'final' => {},
}
puts symbolize(test)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment