From: Robert Klemme Date: 2004-03-04T18:04:42+09:00 Subject: Re: dynamic assignment of instance variables "Gerard A.W. Vreeswijk" schrieb im Newsbeitrag news:d7a05cff.0403040028.33612745@posting.google.com... > Thanks for pointing out the existence of Object#instance_variable_set > (which, of course, Ruby ri v1.8b knows about). > > But then I think Ruby should have a method Object#attribute_set (and > then also a method Object#attribute_get of course), so that we can set > accessible atributes directly so that we are able to say: > > Person.new( :name => 'John', :born => '2003') # (1) > > rather than > > Person.new(:@name => 'John', :@born => '2003') # (2) > > or even > > Person.new(:name= => 'John', :born= => '2003') # (3) > > I this respect, I think it is relevant to quote a 1993 post of Matz [ > http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/68955 ], > where he says: > >Subject: Re: instance_variable_set question > >Newsgroups: comp.lang.ruby > >Date: 2003-04-09 01:32:15 PST > > > > > >Hi, > > > >In message "Re: instance_variable_set question" > > on 03/04/09, Phil Tomson writes: > >| > >|It _is_ a bit confusing, though - if you made an attr_accessor for > @bar, > >|you refer to it as :bar, not :@bar : > > > >You're specifying attribute names (i.e. exporting method names), > which > >does not contain "@" in them, not instance variable names. > >attr_accessor defines methods that use instance variables which names > >are "@"+attribute-name. > > > > matz. > > I think a method Object#attribute_set should exist, to enable straight > and dynamic access to attributes when we want to, and to avoid > counterintuitive calls like (2) or (3) in such cases. > > What do you think? I think that there is a subtle difference between "instance variables" and "attributes": an instance variable is a "physical thing", i.e., an instance does in fact have a variable defined that carries a value. An attribute OTOH is something seen from the outside that does not necessarily relate to an instance variable, although attr, attr_accessor and the like tend to make people think they are tied together. It's perfectly legal to have an attribute that has no 1:1 relationship with an instance variable: class Foo def initialize; @bar = []; end def size; @bar.size; end def size=(s) if s > size @bar.concat( Array.new(s-size, nil) ) elsif s < size @bar.slice!(s..-1) end end end Apart from that someone might have redefined attr, attr_accessor etc. to generate other methods than the default methods... So basically, I'd leave it as it is since the naming difference reflects a semantic difference. Regards robert