Joel VanderWerf
4/27/2009 10:48:00 PM
Brian Hartin wrote:
> Hi there,
>
> When a class mixes in a module containing 'attr_accessor :foo', it must
> then use 'self.foo = ...' instead of simply 'foo = ...'. While I prefer
> 'self.foo' for clarity's sake, I am stumped as to _why_ this is
> required. For example:
>
> module A
> attr_accessor :a
> end
>
> class B
> include A
>
> def bar
> a = "bar"
> end
>
> def baz
> self.a = "baz"
> end
> end
In B#bar, ruby's parser sees "a = ..." and assumes that "a" is local
variable, rather than attempting to call #a= (the writer method). This
has the advantage that, since local variables always "shadow" methods of
the same name, you can write code with the confidence that you are not
invoking some method defined in the class (or somewhere up the ancestor
chain) that you hadn't noticed. For one thing, this makes it easier to
write code that knows as little as possible about its context, and hence
can be shared around by Module#include or even copy-n-paste.
It is, however, a disadvantage for DSL design, but that's another story...
--
vjoel : Joel VanderWerf : path berkeley edu : 510 665 3407