Home > Enterprise >  Ruby instance variables problem using '==' in if condition
Ruby instance variables problem using '==' in if condition

Time:04-03

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.

CodePudding user response:

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.

CodePudding user response:

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!

  • Related