[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

adding object attributes

Artur Merke

12/10/2004 10:01:00 AM

4 Answers

Patrick Gundlach

12/10/2004 11:09:00 AM

0


[...]

> Is there a shorthand notation for adding attributes to an object?

what about

class << a
attr_accessor :b
end

?

Patrick

dblack

12/10/2004 11:38:00 AM

0

Artur Merke

12/10/2004 12:06:00 PM

0

Robert Klemme

12/10/2004 12:23:00 PM

0


"David A. Black" <dblack@wobblini.net> schrieb im Newsbeitrag
news:Pine.LNX.4.61.0412100332320.5050@wobblini...

> 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:

Alternatively Artur can use OpenStruct, where you can add attributes even
more dynamic:

:25:55 [source]: irbs -r ostruct
>> a = OpenStruct.new([:a])
=> <OpenStruct a=nil>
>> a.a
=> nil
>> a.dummy = "hello world"
=> "hello world"
>> a.dummy
=> "hello world"

You can even inherity OpenStruct, if you want to add additional methods:

>> class A < OpenStruct
>> def my_method() puts "buh!" end
>> end
=> nil
>> a=A.new
=> <A>
>> a=A.new [:a]
=> <A a=nil>
>> a.my_method
buh!
=> nil
>> a.dummy = "hello"
=> "hello"
>> a.dummy
=> "hello"
>> a
=> <A a=nil dummy="hello">

Or you use a hash - that might be appropriate in some circumstances, too.

Kind regards

robert