From: "David A. Black" Date: 2004-12-10T20:38:06+09:00 Subject: Re: adding object attributes Hi -- On Fri, 10 Dec 2004, Artur Merke wrote: > Hi > > class A > attr_accessor :a > end > > a= A.new > b= A.new > > #this adds a new attribute to the object 'b' > def b.dummy > @dummy > end > def b.dummy=(val) > @dummy= val > end > > b.dummy= "hello world" > print "\n", b.dummy > > Is there a shorthand notation for adding attributes to an object? > > For example one could think of the equivalent of adding an attribute to a > class, like > > b.attr_accessor(:dummy) #illegal in ruby > > Of course I could define a sort of public 'attr_accessor' for the class > 'A' by myself, but I do NOT want to change/extend the class, only some objects. > > any suggestions? What you want to do is use attr_accessor -- but, as you say, not in 'A', but rather in the singleton class of 'b'. You would do this like this: class << b attr_accessor :dummy end (A singleton class is anonymous, so you have to use the "<< object" notation to "fish" for it from the object whose singleton class it is.) In fact, when you do: def b.dummy ... you are inserting a method into exactly the same class. Opening up the class, however, makes it possible to use class methods, like attr_accessor. David -- David A. Black dblack@wobblini.net