# Turn nested hashes into nested ostructs

**URL:** <https://www.ruby-forum.com/t/turn-nested-hashes-into-nested-ostructs/124611>\
**Category:** Ruby\
**Created:** [December 31, 2007, 1:23am UTC](https://www.ruby-forum.com/t/turn-nested-hashes-into-nested-ostructs/124611 "2007-12-31T01:23:20Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![mgreenly](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/85f322/32.png) [@mgreenly](https://www.ruby-forum.com/u/mgreenly)\
**Post date:** [December 31, 2007, 1:23am UTC](https://www.ruby-forum.com/t/turn-nested-hashes-into-nested-ostructs/124611/1 "2007-12-31T01:23:20Z")

</div>

I just thought I’d share this on the off chance anyone would find it  
useful.  
It simply turns a nested hash into a nested ostruct.

require ‘ostruct’  
class NestedOstruct  
def self.new(hash)  
OpenStruct.new(hash.inject({}){|r,p| r[p[0]] = p[1].kind\_of?(Hash)  
?  
NestedOstruct.new(p[1]) : p[1]; r })  
end  
end

Which allows you to do this…

> > a = NestedOstruct.new( :b =\> { :c =\> { :d =\> {:e =\> 42 } } } )  
> > =\> #\<OpenStruct b=#\<OpenStruct …\>\>
> 
> > a.b.c.d.e  
> > =\> 42

It’s pretty basic but I found the NestedOstruct with YAML::load\_file  
pretty  
useful today.
