Asp Forum
Home
|
Login
|
Register
|
Search
Forums
>
comp.lang.ruby
turn nested hashes into nested ostructs
Michael Greenly
12/31/2007 12:22:00 AM
[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.michaelg...
Servizio di avviso nuovi messaggi
Ricevi direttamente nella tua mail i nuovi messaggi per
turn nested hashes into nested ostructs
Inserendo la tua e-mail nella casella sotto, riceverai un avviso tramite posta elettronica ogni volta che il motore di ricerca troverà un nuovo messaggio per te
Il servizio è completamente GRATUITO!
x
Login to ForumsZone
Login with Google
Login with E-Mail & Password