Skip to content

Instantly share code, notes, and snippets.

@spangenberg
Created August 18, 2011 22:59
Show Gist options
  • Save spangenberg/1155483 to your computer and use it in GitHub Desktop.
Save spangenberg/1155483 to your computer and use it in GitHub Desktop.
Hash methods
require 'ostruct'
class Hash
def key_strings_to_symbols!
r = Hash.new
self.each_pair do |k, v|
if k.kind_of?(String) && k =~ /^:/
v.key_strings_to_symbols! if v.kind_of?(Hash) && 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) && v.respond_to?(:key_strings_to_symbols!)
r[k] = v
end
end
self.replace(r)
end
def to_struct!
key_strings_to_symbols!
r = self.values
r.map! do |v|
if v.kind_of?(Hash) && v.respond_to?(:to_struct!)
v.to_struct!
else
v
end
end
klass = Struct.new(*keys.map(&:to_sym))
klass.new(*r)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment