local state variables unique to different objects

J

Jason Lillywhite

Is there a way to get local state variables to be unique for different
objects? See my example bank account:

class Acc
@@balance = 100
def withdraw( amount )
if @@balance >= amount
@@balance = @@balance - amount
else
"Insufficient Funds"
end
end
@@balance
end

irb(main):012:0> check1 = Acc.new
=> #<Acc:0xb7dc2f14>
irb(main):013:0> check1.withdraw 50
=> 50
irb(main):014:0> check1.withdraw 40
=> 10
irb(main):015:0> check1.withdraw 25
=> "Insufficient Funds"

This is great - but if I create a new object 'check2' it doesn't start
with a new balance of 100. What am I doing wrong here?

irb(main):016:0> check2 = Acc.new
=> #<Acc:0xb7db08c8>
irb(main):017:0> check2.withdraw 40
=> "Insufficient Funds"
I wanted this to return 60
 
J

Joel VanderWerf

Jason said:
Is there a way to get local state variables to be unique for different
objects? See my example bank account:

class Acc
@@balance = 100
def withdraw( amount )
if @@balance >= amount
@@balance = @@balance - amount
else
"Insufficient Funds"
end
end
@@balance
end

@@balance is a _class_ variable, shared by all instances of the class
(and potentially subclasses), you probably want an instance variable:

class Acc
def initialize bal
@balance = bal
end
def withdraw( amount )
if @balance >= amount
@balance = @balance - amount
else
"Insufficient Funds"
end
end
end

acc = Acc.new 100
puts acc.withdraw(12)
puts acc.withdraw(120)
 
J

Jason Lillywhite

ah, thank you.

Interesting how in Lisp (Scheme) you have to do:

(begin (set! balance (- balance amount))
balance)

to decrement the balance and change it's state - using the set!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
473,769
Messages
2,569,577
Members
45,054
Latest member
LucyCarper

Latest Threads

Top