红宝石破碎的简单银行类

时间:2014-10-28 05:53:24

标签: ruby instance-variables

我正在创建一个简单的银行业务程序,但它在第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

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

1 个答案:

答案 0 :(得分:3)

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

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

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

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