On 11/3/06, Learning Ruby <learningruby / gmail.com> wrote:
> On 11/3/06, Jon Egil Strand <jes / luretanker.no> 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
> > such you don't need to store it's value.
> >
> > Actually you don't need it at all, you can instead go for:
> >
> >   def withdraw(amt)
> >     if ((balance - amt) > 500.00)
> >       self.balance -= amt
> >       puts balance
> >     else
> >       puts 'No Balance'
> >     end
> >   end
> >
> >
> > While we're at it, I prefer to separate calculations from output to
> > screen, and instead go for:
> >
> >   def withdraw(amt)
> >     raise "You're broke" if balance - amt <= 500
> >     self.balance -= amt
> >   end
> >
> >
> > combined with:
> >
> >
> >   s.withdraw(200.00)
> >   puts s.balance
> >
> > This does withdraw in one place and shows balance in another.
> >
> >
> > If you now do multiple withdraws, sooner or later you will raise the
> > "You're broke" run-time error. Which you then have to catch. Unless you've
> > read about ruby's exception handling you're in for a treat. Exception
> > handling is very handy, and as always, Ruby does it in an consistent and
> > intuitive way.
> >
> > --
> > Jon Egil Strand
> >
> >
>
> 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)