0

I am creating a Account which should display,withdraw the balance only when the correct is passed as parameter.I am facing a issue in which on passing the correct pin, the balance is not shown instead i am getting an "incorrect Pin" Below is the code of my Account Class:

class Account
  attr_reader :name
  attr_reader :balance
  def initialize(name,balance=100)
    @name = name
    @balance = balance
  end
  def display_balance(pin_number)
    if pin_number == @pin
      puts "Balance : #{@balance}"
    else
      puts pin_error
    end
  end
  def withdraw(pin_number,amount)
    if pin_number == @pin
      @balance -= amount
      puts "Withdraw #{amount}. New balance: #{@balance}" 
    else
      puts pin_error
    end
  end
  private
  def pin
    @pin = 1234
  end
  def pin_error
    return "Access denied: incorrect PIN."
  end
end
checking_account = Account.new("Yash",10000)
checking_account.display_balance(123)
checking_account.display_balance(1234)

Above code is showing output as:

Access denied: incorrect PIN.
Access denied: incorrect PIN.

The expression "if pin_number == @pin" is not comparing as desired as on giving correct PIN(1234) it should display the balance.

2 Answers 2

4

The only place where @pin is assigned is in pin. But pin never gets called, thus @pin never gets assigned. In Ruby, un-initialized instance variables evaluate to nil, so @pin will always evaluate to nil.

Sign up to request clarification or add additional context in comments.

Comments

0

I hope this will solve your problem:

class Account
  attr_reader :name
  attr_reader :balance

  def initialize(name,balance=100)
    @name = name
    @balance = balance
    pin #set @pin from here
  end

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

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

  private

  def pin #this method was not called from your code, that was the issue
    @pin = 1234
  end

  def pin_error
    return "Access denied: incorrect PIN."
  end
end
checking_account = Account.new("Yash",10000)
checking_account.display_balance(123)
checking_account.display_balance(1234)

Thanks!

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.