------ art_22429_14660045.1162566184476 Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit Content-Disposition: inline On 11/3/06, dblack / wobblini.net <dblack / wobblini.net> wrote: > > Hi -- > > On Fri, 3 Nov 2006, Learning Ruby wrote: > > > On 11/3/06, Jan Svitok <jan.svitok / gmail.com> wrote: > >> > >> > 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 - mt ? > >> > >> 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 alue) > @balance alue > end > > Again, there's no magic in the naming; you could also do: > > def change_balance_to(value) > @balance alue > 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 alue) > @something alue > 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 > > Thanks David for a very clear explanation and clearing my doubts. What a coincidence that just the other day I bought and have started reading your excellent book Ruby for Rails - a must for every Ruby beginner. ------ art_22429_14660045.1162566184476--