From: "ara.t.howard" Date: 2007-10-10T13:01:54+09:00 Subject: Re: YAML to Struct On Oct 9, 2007, at 5:46 PM, Andrew Hite wrote: > Is it possible to take YAML and turn it into a Struct? I want to take > something that looks like this: > > key_1: Value 1 > key_2: Value 2 > > And turn it into an object with accessors...and I'm assuming a Struct > would be my best bet. I'm relatively new to the concepts of YAML and > the Struct class, so I'm banging my head against the wall trying to > figure this out. > > Any ideas? > -- > Posted via http://www.ruby-forum.com/. > cfp:~ > cat a.rb require 'yaml' class Hash def to_struct class_name = nil klass = unless class_name Struct.new *keys.map{|key| key.to_sym} else Struct.new class_name.to_s, *keys.map{|key| key.to_sym} end klass.new *values end end hash = YAML.load DATA.read struct = hash.to_struct p struct p struct.x p struct.key p struct.a __END__ x : y key : value a : 42 cfp:~ > ruby a.rb # a=42, x="y", key="value"> "y" "value" 42 a @ http://codeforpeople.com/ -- it is not enough to be compassionate. you must act. h.h. the 14th dalai lama