Hi --
> Thanks. This is a much better code. One more related thing that confuses
me
> is that I thought all instance variables of a class are private to the
> class. Then are the private instance variables inherited by a sub-class?
If
> yes, then in my Savings class withdraw method, can I write @balance -=
amt
> instead of self.balance -= amt ?
sure. the difference is whether you're getting the var from the inside
(@balance) or outside (self.balance)
@balance will be a tiny bit faster, self.balance is more flexible as
you can change the inner implementation later without breaking other
things (i.e. you can add conditions checking befor the var is actually
set)
Coming from a Java background the confusion still exists. I still can't
fathom the difference between @balance and self.balance as mentioned by you
(Jan Svitok) above. Does not the self.balance mean the instance variable
balance of current object? And is not @balance the same thing?
It all starts with the instance variable, @balance. The balance
method is simply a wrapper around it:
def balance
@balance
end
There's no special link between the names; you could also write:
def my_balance
@balance
end
and then do:
obj.my_balance
It's just a method whose return value happens to be the current value
of an instance variable.
Then there's the other half: the setter-method. Same thing: it's just
a wrapper:
def balance=(value)
@balance = value
end
Again, there's no magic in the naming; you could also do:
def change_balance_to(value)
@balance = value
end
It's customary in such cases, however, to name the get and set methods
with the same name as the instance variable they get and set. In
fact, this idiom:
def something
@something
end
def something=(value)
@something = value
end
is so common, that Ruby gives you a shortcut: instead of writing those
lines of code, you can just do:
attr_accessor :something
and Ruby will write the methods for you. That's what you've done with
"balance".
One way or another (manually or with an attr method), you have to
define these methods; you can't just say "obj.blah" and expect to get
the value of @blah.
David
···
On Fri, 3 Nov 2006, Learning Ruby wrote:
On 11/3/06, Jan Svitok <jan.svitok@gmail.com> wrote:
--
David A. Black | dblack@wobblini.net
Author of "Ruby for Rails" [1] | Ruby/Rails training & consultancy [3]
DABlog (DAB's Weblog) [2] | Co-director, Ruby Central, Inc. [4]
[1] Ruby for Rails | [3] http://www.rubypowerandlight.com
[2] http://dablog.rubypal.com | [4] http://www.rubycentral.org