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.
I agree. This should be basic Ruby (and perhaps basic OO).
Apart from that someone might have redefined attr, attr_accessor etc. to
generate other methods than the default methods…
That would be no problem I think, because this redefinition would be reflected
in the accessors themselves, i.e., the behaviour of the accessors would
change along.
It’s just that I am too lazy to write the method “attribute_set”
myself AND that this method seems standard enough to be expected as
Ruby built-in method.
Or does my requirement clash with obvious Ruby or OO philosophy?
Please let me know. Thanks.
sh-2.04$ cat try_accessors.rb
class Object
def attribute_set(k, v) # should be built-in
send “#{k}=”, v # interpolation, yuck
end
end
class Person
attr_accessor :name, :born
def initialize(args)
args.each do |attr,val|
attribute_set(attr, val) # should raise an error if attr’s are not settable
end
end
end
p Person.new(:name => ‘John’, :born => ‘2003’)
sh-2.04$ ./try_accessors.rb
#<Person:0x2a876d8 @born=“2003”, @name=“John”>
sh-2.04$ _
···
On Thu, 4 Mar 2004 10:02:44 +0100, “Robert Klemme” bob.news@gmx.net wrote: