From: Holden Glova Date: 2002-05-04T20:22:19+09:00 Subject: Re: dynamically assigning instance variables -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On Sat, 04 May 2002 09:43, Berger, Daniel wrote: > Hi all, > > Yep, still trying to unwrap my brain from Perl and re-wrap it in Ruby... > > Is there a way to dynamically assign instance variables? > > class SomeClass > def initialize(hash) > hash.each do |key,val| > @#{key} = val # Doesn't work > end > end > end > > Is there a better way to do this? > > Thanks in advance. > > Regards, > > Dan I'll add something to pile, here is something I used as a mixin where ever i needed to this. # # Builds object attributes from a supplied Hash # module HashAttrBuilder # # Builds the object attributes from the supplied Hash. # # attributes: A Hash with each key being a Symbol # def build_instance_vars(attributes) attributes.each do |k, v| name = k.id2name value = v.type == String ? "'" + v + "'" : v instance_eval(<<-EOS) class << self attr_accessor :#{name} end EOS send("#{name}=", v) end end end - -- Signed, Holden Glova -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.0.6 (GNU/Linux) Comment: For info see http://www.gnupg.org iD8DBQE808X1+mF116Lw2cQRAk7+AKCETHtHfNCnj5/T+xrPF2w9Of63pgCfTRmE Ovta6egpqYRQFresjVRZPIQ= =kBeb -----END PGP SIGNATURE-----