如何让这个简单的银行系统保持更新的平衡?

时间:2014-07-02 12:42:55

标签: ruby console

def account()
    puts "ENTER ACCOUNT NUMBER"
    accountnumber = gets.chomp
    puts "SUCCESS"
    modeselect()
end

def modeselect()
    puts "WHAT WOULD YOU LIKE TO DO?"
    mode = gets.chomp
    mode.upcase!
    case mode
        when "DEPOSIT"
        deposit()
        else
        account()
    end
end

def deposit()
    balance = 0
    puts "ENTER DEPOSIT AMOUNT"
    depositamount = gets.chomp.to_i
    balance == balance + depositamount
    puts "DEPOSIT SUCCESSFUL, BALANCE = #{balance}"
    modeselect()
end


account()

目前,代码完成了存款,但是当再次运行存款方式时,余额被重置,我试图让它在上次运行时跟进,因此余额会在每次运行后永久更新沉积物。

我该怎么做?感谢。

2 个答案:

答案 0 :(得分:0)

有三个原因使得余额看起来好像正在重置。

首先,余额存储在一个变量中,该变量的范围包含在存款功能块中。这意味着当函数完成时该变量具有的任何值都不会被保留。事实上,变量不再可访问。您可以使用@balance

的Sergio建议使用实例变量

其次。输入存款功能块后,余额将立即显式设置为0。解决此问题的一个选项是,如果尚未为其分配值,则仅为@balance赋值0。您可以使用@balance ||= 0

执行此操作

第三。存款功能块==的第四行上的运算符是比较运算符而不是赋值运算符。我相信您打算使用=

def account()
    puts "ENTER ACCOUNT NUMBER"
    accountnumber = gets.chomp
    puts "SUCCESS"
    modeselect()
end

def modeselect()
    puts "WHAT WOULD YOU LIKE TO DO?"
    mode = gets.chomp
    mode.upcase!
    case mode
        when "DEPOSIT"
        deposit()
        else
        account()
    end
end

def deposit()
    @balance ||= 0
    puts "ENTER DEPOSIT AMOUNT"
    depositamount = gets.chomp.to_i
    @balance = @balance + depositamount
    puts "DEPOSIT SUCCESSFUL, BALANCE = #{@balance}"
    modeselect()
end

account()

答案 1 :(得分:0)

如果您不想使用@balance等实例变量,则可能需要在调用方法/函数时将变量balance传递给"保留"值。这样的事情(注意这段代码有效,但有严重的缺陷)

def account()
    balance ||= 0
    puts "ENTER ACCOUNT NUMBER"
    accountnumber = gets.chomp
    puts "SUCCESS"
    modeselect(balance)
end

def modeselect(balance)
    puts "WHAT WOULD YOU LIKE TO DO?"
    mode = gets.chomp
    mode.upcase!
    case mode
        when "DEPOSIT"
        #balance ||= 0
        deposit(balance)
        else
        account()
    end
end

def deposit(balance)        
    puts "ENTER DEPOSIT AMOUNT"
    depositamount = gets.chomp.to_i
    balance = balance + depositamount
    puts "DEPOSIT SUCCESSFUL, BALANCE = #{balance}"
    modeselect(balance)
end


account()