Turn nested hashes into nested ostructs

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.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs