turn nested hashes into nested ostructs

Discussion in 'Ruby' started by michael greenly, Dec 31, 2007.

  1. [Note: parts of this message were removed to make it a legal post.]

    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.

    --
    Michael Greenly
    http://blog.michaelgreenly.com
    michael greenly, Dec 31, 2007
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Ben Holness

    Hashes of Hashes via subs

    Ben Holness, Oct 5, 2003, in forum: Perl
    Replies:
    8
    Views:
    549
    Ben Holness
    Oct 8, 2003
  2. Steven Arnold

    using hashes as keys in hashes

    Steven Arnold, Nov 23, 2005, in forum: Ruby
    Replies:
    3
    Views:
    155
    Mauricio Fernández
    Nov 23, 2005
  3. kazaam
    Replies:
    12
    Views:
    260
    Matthias Wächter
    Sep 13, 2007
  4. Neela megha shyam Chivukula

    On Hashes - How the hashes printing works?

    Neela megha shyam Chivukula, May 27, 2009, in forum: Ruby
    Replies:
    4
    Views:
    214
    Markus Schirp
    May 28, 2009
  5. Tim O'Donovan

    Hash of hashes, of hashes, of arrays of hashes

    Tim O'Donovan, Oct 27, 2005, in forum: Perl Misc
    Replies:
    5
    Views:
    201
Loading...

Share This Page