From: James Britt Date: 2009-02-11T13:35:18+09:00 Subject: Re: redefining @my_attr= Mike Cahill wrote: > I want to write a generic validator that ensures an attr value is in a > list before assigning, and if not, assigns a default. It works for > self.attrib='value', and Dummy.new.attrib='value', but not > @attrib='value' within the class. The connection between a method foo=(val) and some instance variable @foo is essentially coincidental. When you use a class method such as attr_accessors it dynamically creates code that defines accessor methods, and in those methods uses an instance variable with a matching name. But there's no reason the instance variable in those accessors methods could not called something else. It just makes a certain sense to use an obvious naming convention; it's so much easier to track what your code is doing. And it creates (for better or worse) the illusion of public "properties" (as, for example, what Java has). There's nothing to stop other methods from manipulating those instance variables; they have no intrinsic connection to any particular methods, no matter what they are named. # Runs, but pedantic def foo=(x); @bar=x;end def baz; @bar; end def foo; 47; end When you do @attrib = 47 you are working directly with the instance variable, not with a method that might just happen to have a matching name. -- James Britt www.happycamperstudios.com - Wicked Cool Coding www.jamesbritt.com - Playing with Better Toys www.ruby-doc.org - Ruby Help & Documentation www.rubystuff.com - The Ruby Store for Ruby Stuff