红宝石破碎中的简单银行类



我正在创建一个简单的银行程序,但它在第35行一直出错——我是不是用实例变量设置错误并初始化了它们?

为什么我无法访问@balance实例变量?

class Person
    attr_accessor :name, :initAmount
    def initialize(name, initAmount = 0)
        @name = name
        @initAmount = initAmount
        puts "Hi, #{name}.  You have $#{initAmount} on hand!"
    end
end
class Bank
    def initialize(bank_name, balance = 0, deposit = 0)
        @bankName = bank_name
        @balance = balance
        @deposit = deposit
        puts "#{bank_name} bank was just created."
    end

    def open_account(name)
        @balance = @initAmount
        puts "#{@name}, thanks for opening an account at #{@bankName}!" 
    end
    def withdrawal(name, amount)
        if amount > 0
            @balance -= amount
            puts "#{name} withdrew $#{amount} from #{@bankName}.  #{name} has #{@balance}.  #{name}'s account has #{@balance}."
        end
    end
    def deposit(name, amount)
        if amount > 0 
            @balance += amount
            puts "#{name} deposited $#{amount} to #{@bankName}. #{name} has #{@balance}. #{name}'s account has #{@balance}."
        end
    end
    def transfer(name, bankName, amount)
        if @name = name
           @balance -= amount
           puts "#{name} have transfered $#{amount} from #{@bankName} account to #{@bankName}.  Your new balance is $#{@balance}."
        else
            puts "Wrong username"
        end
    end
end
chase = Bank.new("JP Morgan Chase")
wells_fargo = Bank.new("Wells Fargo")
me = Person.new("Tom", 500)
friend1 = Person.new("hon", 1000)
chase.open_account(me)
chase.open_account(friend1)
wells_fargo.open_account(me)
wells_fargo.open_account(friend1)
chase.deposit(me, 200)
chase.deposit(friend1, 300)
chase.withdraw(me, 50)
chase.transfer(me, wells_fargo, 100)
# chase.deposit(me, 5000)
# chase.withdraw(me, 5000)
# puts chase.total_cash_in_bank
# puts wells_fargo.total_cash_in_bank

请帮我澄清我做错了什么。实例变量背后的本质不是你可以将它们作为属性分配给任何创建的对象吗?

open_account中,您正在访问变量@initAmount@name,但尚未在同一类中定义它们。

要访问Person的属性,您应该使用该对象。

您的方法需要一个Person对象,最好正确命名它。例如:

def open_account(person)
  @balance = person.initAmount
  puts "#{person.name}, thanks for opening an account at #{@bankName}!" 
end

相关内容

  • 没有找到相关文章

最新更新