为什么我必须引用该方法而不是@variable?

时间:2019-05-31 21:27:27

标签: ruby

了解类,方法,全局变量,实例变量和类变量。

建立一个非常基本的帐户类,而提现方法需要2个变量:pin_number,金额。我不明白为什么这两个都不返回true。

如果要退出的话,在撤回方法中:

 if pin_number == pin 

调用pin方法返回@pin且语句为真

 if pin_number == @pin 

语句返回假

我的第一个假设是私有标签,但是我删除了它,但仍然没有返回true。

class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == pin
        @balance -= amount
        puts "Withdrew #{amount}. New balance: $#{@balance}."
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error 
      end
    end

    def deposit(amt)
      @balance += amt
      puts @balance
    end
private
    def pin
    @pin = '1234'
  end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)

1 个答案:

答案 0 :(得分:2)

您看到的效果是因为您仅在@pin方法内分配了实例变量pin

也就是说,直到您在比较中调用pin时,它才被设置。当您尝试直接使用@pin时,它尚未初始化。

@pin中分配initialize变量,然后一切正常。

class Account
  attr_reader :name, :balance
  def initialize(name, balance=100)
    @name = name
    @balance = balance
    @pin = '1234'
  end

  public
    def withdraw(pin_number, amount)
      if pin_number == @pin
        @balance -= amount
        puts "Withdrew #{amount} from pin #{@pin}, new bal is #@balance"
      else
        puts pin_error
      end
    end

    def display_balance(pin_number)
      if pin_number == @pin
        puts "Balance: $#{@balance}."
      else
        puts pin_error 
      end
    end

    def deposit(amt)
      @balance += amt
      puts "Deposited #{amt} to pin #@pin, new bal is #@balance"
    end

 def pin_error
    "Access denied: incorrect PIN."
  end
end

checking_account = Account.new('Jensen', 904)
checking_account.deposit(5)
checking_account.withdraw('1234',900)

这产生

Deposited 5 to pin 1234, new bal is 909
Withdrew 900 from pin 1234, new bal is 9