From: Rich Kilmer Date: 2002-04-02T23:22:12+09:00 Subject: RE: Creating an instance of a class without calling initialize() > -----Original Message----- > From: Harry Ohlsen [mailto:harryo@zip.com.au] > Sent: Monday, April 01, 2002 7:11 PM > To: ruby-talk ML > Subject: Re: Creating an instance of a class without calling initialize() > > "Rich Kilmer" wrote in message > > > You actually may want to recommend that he use: > > > > obj = new > > > > FOR EACH ATTRIBUTE > > obj.instance_eval "@#{attributeName}=#{attributeValue}" > > END > > > > That way it works for attributes that do not have writer methods but > > only reader methods (ie. Foo.x but not Foo.x=) > > Unfortunately, that won't work very well if the attribute > value is an instance of an arbitrarily complex class, since > what it's effectively trying to do is de-serialise/re-serialise > atrributeValue as text :-). > My bad here...I should have written: obj = new FOR EACH ATTRIBUTE eval "obj.instance_eval {@#{attributeName}=attributeValue}" END That way what you are doing is a local eval (which has attributeValue in its local scope) and passing a block to instance_eval (which will then have @'attributeName' in its local scope) so string stuff is avoided. Assuming the attributeName = x, this would be the same as doing obj.instance_eval {@x=attributeValue} Cool, huh? -Rich