Welcome to Ruby!
On Sun, 17 Aug 2003, Meino Christian Cramer wrote:
Ruby also has those keywords. The stuff you're asking about below> 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:
> As I currently (try to) understand, Ruby does it somehow different.
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.)
It's just initialize (no 'r')> class A
> def initializer( k_a )
Actually your code is simpler than that: it just sets an instance> a = k_a
> will declare a class A with a "totally private" attribute "a", which
> only can be accessed vie get/set-combos.
variable. At that point, nothing else has happened; there are no
(They're actually methods, not keywords.)>> > Now I found (for me astonishling) two keywords:
> which (seems to) totally "inifiltrate" the principle of data hiding
> and encapsulation.
OK :-)> PLEASE!
> Dont misundertstood my words as any kind of critism on Ruby !!!
attr_reader and attr_writer basically serve the purpose of saving> 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?
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:
# define a get method for attribute a
# define a set method for attribute a
a = x
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:
or, even more concisely:
attr_accessor :a # read and write in one
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
David Alan Black