Hi --

On Sun, 17 Aug 2003, Meino Christian Cramer wrote:

> From: dblack / superlink.net
>
> > attr_reader and attr_writer basically serve the purpose of saving
> > keystrokes; they don't do anything that you can't do, at slightly
> > greater length, by hand.
>
>   Yes...
>   But...did I understood so far:
>   "Setting" an attribute with "attr_accessor" means it is world
>   readable and writeable (or speaking the UNIX-way, it is
>   rw-rw-rw ;) ?

You're not setting it with attr_accessor; you're using attr_accessor
to automatically create two methods for you.  One reads an instance
variable, the other sets it.  If you don't want those operations to
be possible, then you wouldn't want to create those methods.

> > Specifically, they automatically create some simple get/set methods
> > for instance variables.  Once an instance variable has these methods,
> > it can be used in an attribute-like way.  (There's actually no
> > separate 'attribute' type or category; it's all just methods, with
> > attribute-ness being essentially a stylistic component.)
>
>   HU?
>
>   Until this point I thought, "attributes" _are_ instance variables...
>   (haveing C++ in mind...)

I had Ruby in mind :-)  Didn't mean it to apply to all languages.  I
don't know C++, so I can't make a detailed comparison, but in Ruby,
when you send a message to an object -- say, obj.a -- it always means
that you are asking the object to execute the method corresponding to
the message.  There's no separate concept of "retrieving an
attribute", at least not at the language level.  It's conventional to
use instance variables to bring about attribute-like functionality.
But you can use instance variables for other things, and you can do
things behind the scenes in your setter and getter methods that don't
involve instance variables.

A simple example of some things you can do:

  class C
    def state=(s)    # as in United States :-)
      raise ArgumentError unless %w{ AR AZ CA DE }.include?(s.upcase)
      @st = s.upcase
    end

    def state
      @st.dup      # solving the problem I mentioned earlier
    end
  end

  c = C.new
#  c.state = "Delaware"   # error
  c.state = "dE"
  p c.state   # "DE"

(Using @st instead of @state is pointless, except to illustrate that
your get/set methods don't actually have to have the same names as
any instance variables you use to implement them.  )


David

-- 
David Alan Black
home: dblack / superlink.net
work: blackdav / shu.edu
Web:  http://pirate.shu.edu/~blackdav