From: Brian Candler Date: 2003-02-20T01:04:35+09:00 Subject: Re: How to test for existence of instance variable? On Thu, Feb 20, 2003 at 12:26:57AM +0900, Paul Brannan wrote: > On Thu, Feb 20, 2003 at 12:02:21AM +0900, Brian Candler wrote: > > #!/usr/local/bin/ruby -w > > mystruct = Struct.new("Mystruct","a","b","c") > > obj = mystruct.new > > > > mystruct.instance_eval { attr_accessor :d } # add a new member > > I don't think this is a good idea, since d isn't recognized as a member: > > irb(main):001:0> mystruct = Struct.new("Mystruct","a","b","c") > => Struct::Mystruct > irb(main):002:0> obj = mystruct.new > => # > irb(main):003:0> mystruct.instance_eval { attr_accessor :d } > => nil > irb(main):004:0> obj.members > => ["a", "b", "c"] Yeah, not sure entirely about that, because even the instance variable is invisible to 'inspect': irb(main):006:0> obj.d="foo" "foo" irb(main):008:0> obj # # where's d? But it does work. > It would be better, I think, to inherit from Struct and write a new > method to dynamically add a member. You can then define members() in > the derived class to include "d" as a member, and you can add a new > method to easily lookup whether a given member is already defined. I want a general method to add a member to the class dynamically, so if there were Struct#add_member I would happily use it. I don't see what you mean about subclassing though. Creating SuperStruct as a subclass of Struct would mean that it had two sets of members (the members created for the initial Struct and then the members I added later) which would be horrible - better just to rewrite Struct from scratch, which I don't fancy. OTOH, if I wanted to learn the internals of Struct I could add a new method 'add_member' without subclassing it at all. Subclassing *instances* of Struct is not what I want either, since it's not possible to change existing objects from type A to type B (even if B is a subclass of A) after they have been created. Regards, Brian.