Skip to content

Instantly share code, notes, and snippets.

@louismullie
Created June 17, 2012 17:30
Show Gist options
  • Save louismullie/2945123 to your computer and use it in GitHub Desktop.
Save louismullie/2945123 to your computer and use it in GitHub Desktop.
Convert nested hashes to nested structs
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
@louismullie
Copy link
Author

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.:

  hash =  { know_that: { "this" => "won't be converted" }, see_if: { this: { will: "be converted" } }
  struct = hash_to_struct(hash)
  struct.know_that # => { "this" => "won't be converted" }
  struct.see_if.this.will # => "be converted"

This achieves 20x better performance than using nested hashes!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment