Help with Saving Account (Ruby)

Here is my code:

module SavingsAccount
  def self.interest_rate(balance)
    if balance < 1000.00 && balance >= 0.00
      return 0.5
    elsif balance >= 1000.000 && balance < 5000.00
      return 1.621
    elsif balance >= 5000.00
      return 2.475 
    elsif balance < 0.00
      return -3.213  # Negative interest rate for negative balances
    end 
  end

  def self.annual_balance_update(balance)
    # Use absolute value for calculating interest, but return updated balance considering original sign
    if balance < 0.00
      # For negative balances, calculate interest based on positive balance (abs) and return the updated balance
      return ((balance.abs * (self.interest_rate(balance) / 100)) + balance).to_f
    else 
      # For positive balances, calculate interest based on the balance and return the updated balance
      return ((balance * (self.interest_rate(balance) / 100)) + balance).to_f
    end 
  end

  def self.years_before_desired_balance(current_balance, desired_balance)
    years = 0 
    while current_balance < desired_balance 
      current_balance = self.annual_balance_update(current_balance)
      years += 1 
    end 
    return years 
  end
end

Why does it fails four tests for minimal, small, regular and large negative interest rates.

assert_in_delta(3.213, SavingsAccount.interest_rate(-300.0), 0.000_1)


### Test Failure

Expected |3.213 - -3.213| (6.426) to be <= 0.0001.

It looks like your return value has the sign incorrect. You may need to add a * -1 or something.

1 Like