On 6 February 2013 07:26, FirstName Surname <lists / ruby-forum.com> wrote:

> I see, i thought that you could use these accessors only outside the
> class, not inside it.
> However i'm still not sure what's the point of using the accessor
> instead of directly the instance variable there.
> I suppose it makes sense when a method shouldn't use an instance
> variable "as it is".
>

Yeah, it's a DRY thing.

If there's no other logic in your accessor then `@foo` and `self.foo` are
interchangeable (one has an extra character -- more typing; the other in
theory has an extra function call -- more execution time and memory usage,
although this could well be optimised away for all I know.)

However if you have other code (assertions, last-minute coercions, etc.) in
the accessor, then `@foo` and `self.foo` do different things, and you'd
have to make sure you either duplicate that code from self.foo (WETly) or
be certain that you don't need it in the case in question.

For myself, I use @foo when I'm thinking of the value as an instance
variable (literally a variable, some internal state used for calculations
or whatever, private to the object's scope), and `self.foo` when I'm
thinking of it as a "property" (an attribute that partially describes the
object, visible to the outside world.)

As a general rule I try to avoid bare `foo` since it's not clear whether I
mean a local variable or a property of `self` or something else altogether
(not to mention that `self.foo = 1` is very different from `foo = 1`).

Incidentally, I didn't realise the parser would recognise `price` above as
a function call; I thought lexically it looked like a local variable.  Does
the attr_accessor directive make it more clever?  Are attributes lexically
different from function calls?  Am I overthinking something?

-- 
  Matthew Kerwin, B.Sc (CompSci) (Hons)
  http://matthew.kerwin.net.au/
  ABN: 59-013-727-651

  "You'll never find a programming language that frees
  you from the burden of clarifying your ideas." - xkcd