Created
June 17, 2012 17:30
-
-
Save louismullie/2945123 to your computer and use it in GitHub Desktop.
Convert nested hashes to nested structs
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 hash_to_struct(hash) | |
return hash if hash.keys. | |
select { |k| !k.is_a?(Symbol) }.size > 0 | |
struct = Struct.new( | |
*hash.keys).new(*hash.values) | |
hash.each do |key, value| | |
if value.is_a?(Hash) | |
struct[key] = | |
self.hash_to_struct(value) | |
end | |
end | |
struct | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Recursively converts a hash to a struct. Stops whenever it encounters anything other than a hash, or a hash that does not have symbols as keys, e.g.:
This achieves 20x better performance than using nested hashes!