Hi --

Welcome to Ruby!

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

> Hi,
>
>  as a beginner in C++ I learned that one advantage of OOP over the
>  procedural programming is data hiding and encapsulation.
>
>  In C++ this is achieved via the public:, protected: and private:
>  keywords.
>
>  As I currently (try to) understand, Ruby does it somehow different.

Ruby also has those keywords.  The stuff you're asking about below
isn't instead of them, but in addition to them.  (I don't know C++, so
I'm not sure how close the correspondence is.)

>  class A
>    def initializer( k_a )

It's just initialize (no 'r')

>      @a = k_a
>    end
>  end
>
>  will declare a class A with a "totally private" attribute "a", which
>  only can be accessed vie get/set-combos.

Actually your code is simpler than that: it just sets an instance
variable.  At that point, nothing else has happened; there are no
get/set methods.

> >  Now I found (for me astonishling) two keywords:
>
> 	 attr_reader:
>
>  and
>
> 	 attr_writer:
>
>  which (seems to) totally "inifiltrate" the principle of data hiding
>  and encapsulation.

(They're actually methods, not keywords.)

>  PLEASE!
>
>  Dont misundertstood my words as any kind of critism on Ruby !!!

OK :-)

>  I only want to express my current (mis)understanding of that what I
>  try to understand.
>
>  What is the secret behind attr_reader and attr_writer and how do they
>  support OOP?

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.

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.)

Here's an example:

  class C
    # define a get method for attribute a
    def a
      @a
    end

    # define a set method for attribute a
    def a=(x)
      @a = x
    end
  end

  c = C.new
  c.a = 100      # set the a "attribute" (i.e., call method a= )
  puts c.a       # get the a attribute (i.e., call method a )

That class can be written like this instead:

  class C
    attr_reader :a
    attr_writer :a
  end

or, even more concisely:

  class C
    attr_accessor :a      # read and write in one
  end

The whole attr_* family of methods really just saves some typing.

And of course many combinations and permutations are possible...  I've
just used some simple examples to show some of the basic operations of
attr_*.


David

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