From: dblack@... Date: 2006-11-03T23:46:50+09:00 Subject: Re: Output not clear Hi -- On Fri, 3 Nov 2006, Learning Ruby wrote: > On 11/3/06, Jon Egil Strand wrote: >> >> In your withdraw-method it's not really fitting to use @bal as a class >> variable. It's not needed outside the scope of a single withdraw, and as @bal is an instance variable, not a class variable. > 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 ? The terminology is getting a bit convoluted here. Instance variables are per-object, not per-class, and they're not inherited. But if a method uses one, and that method is available to subclasses, then it will still use the variable -- but "the variable" in the sense of one per object: class C def initialize @n = 100 end def increase_n @n *= 20 end end class D < C def show_n puts "n is #{@n}" end end d = D.new d.increase_n d.show_n The output is: n is 2000 The @n in D's methods is the same (for each instance) as the one in C. As for the @balance -= thing: you can do that, but sometimes there are good reasons not to. You might have a balance or balance= method that does more than just get and set the instance variable. Imagine something like: def last_name=(n) @last_name = n.downcase.capitalize end If you now say: @last_name = "bLaCk", it won't get normalized. (And yes, I know that there's no one rule that governs all last names :-) In such a case, it's better to go through the method: self.last_name = "bLaCk". David -- 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] http://www.manning.com/black | [3] http://www.rubypowerandlight.com [2] http://dablog.rubypal.com | [4] http://www.rubycentral.org