is there a way to add properties to instances and access them later
just like if they were defined in the object's class?
a.newproperty = 123
puts a.newproperty
i know how to dynamically add newproperty to the class of instance 'a',
but is there a way to do it per instance? or do i have to maintain an
explicit hash table on my objects and access these attributes through
the table?
irb(main):018:0> class Magic
irb(main):019:1> def method_missing( meth, *args, &block )
irb(main):020:2> if meth.to_s =~ /^(\w+)=$/
irb(main):021:3> instance_variable_set("@#{$1}", *args)
irb(main):022:3> elsif instance_variables.include? "@#{meth}"
irb(main):023:3> instance_variable_get("@#{meth}")
irb(main):024:3> else
irb(main):025:3* super
irb(main):026:3> end
irb(main):027:2> end
irb(main):028:1> end
=> nil
irb(main):029:0> b = Magic.new
=> #<Magic:0x1b0764>
irb(main):030:0> b.new_property = 123
=> 123
irb(main):031:0> b.new_property
=> 123
Hope that helps.
James Edward Gray II
···
On Oct 6, 2005, at 9:36 PM, ako... wrote:
hello,
is there a way to add properties to instances and access them later
just like if they were defined in the object's class?
a.newproperty = 123
puts a.newproperty
i know how to dynamically add newproperty to the class of instance 'a',
but is there a way to do it per instance? or do i have to maintain an
explicit hash table on my objects and access these attributes through
the table?
is there a way to add properties to instances and access them later
just like if they were defined in the object's class?
a.newproperty = 123
puts a.newproperty
i know how to dynamically add newproperty to the class of instance 'a',
but is there a way to do it per instance? or do i have to maintain an
explicit hash table on my objects and access these attributes through
the table?
I think OpenStruct is what you want to use. If you feel you have to
implement it yourself, or it's not quite right, think about using
method_missing. It is perhaps the most awsomely useful concepts in
Ruby.
···
On 10/6/05, James Edward Gray II <james@grayproductions.net> wrote:
On Oct 6, 2005, at 9:36 PM, ako... wrote:
> is there a way to add properties to instances and access them later
> just like if they were defined in the object's class?