Jay S. wrote in post #1010009:
Thanks for your patience! I meant “protected” not “private”. That
attr_reader and “protected” are independent is an interesting point that
I need to ponder. The 2 reference books that I use (the other is The
Book of Ruby) do not clarify this (at least to me).
Yes. attr_reader :balance is shorthand for writing:
def balance
@balance #same as ‘return @balance’
end
And attr_accessor :balance is shorthand for writing:
def balance
@balance #same as ‘return @balance’
end
def balance=(val)
@balance = val
end
Sometimes, I think it is a waste of time for ruby books to introduce the
attr_accessor family of methods because they mostly confuse. It would
be better for beginners to have to write out their setter and getter
methods by hand. But then consider if you wanted getter and setter
methods for 30 different instance variables? Only after having written
those all out by hand would you see the benefit of being able to write
this instead:
attr_accessor :a, :b, :c, :d, :e, :f, :g, :h, :i, :j, :k …
I am still slightly
confused about part of the rest of your response. I gather that the
method “balance” declared in the attr_reader and in the protected
statement are one and the same: the getter method for the @balance
instance variable. Correct?
Yes, but attr_reader and protected() are not some kind of siamese
pairing. Each one is independent of the other, and they do different
things. For instance, protected() is not shorthand for anything.
Then to
understand how private and protected methods are different from regular
methods, you have to learn more about ‘self’. For instance, when you
write this:
def greet
puts ‘hello’
end
greet
–output:–
hello
That method actually becomes a private method. See how you call it
without a receiver? Private methods cannot be called with a receiver,
and since all methods have to have a receiver (in ruby speak: an
object which receives the :greet message), self becomes the invisible
receiver. self is a ruby variable name that ruby assigns objects to
depending on where you are in your code. The self variable is
constantly changing, and if you call a method without a receiver,
whatever object self is equal to at that moment becomes the receiver.
The ‘receiver’ language is ruby speak. You can translate the above to
mean: "all methods must be called by an object. If I don’t specify an
object when calling a method, then ruby automatically calls the method
with self. Same thing.