Ruby deposit system, algorithm problem

Question 1

Implement a program that meets the following conditions

I have a deposit balance of 100,000 yen in my bank account and I will create a program to withdraw money. -Create a withdraw method to withdraw money ・ When you withdraw money, a fee of 110 yen will be charged, and the message "You have withdrawn ◯◯ yen. The balance is ◯◯ yen" will be displayed (the balance will be the amount after deducting the fee). ・ If you withdraw more than your deposit balance, the message "Insufficient balance" will be displayed. ・ Please refer to the hints below.


def withdraw(balance, amount)
  fee = 110  #Fee
#Display the withdrawal amount and balance, or display as insufficient balance if you withdraw more than the balance
end

balance = 100000  #Balance
puts "How much do you want to withdraw? (It costs 110 yen)"
money = gets.to_i
withdraw(balance, money)

It was a relatively straightforward issue.

Below is the answer.


def withdraw(balance, amount)
  fee = 110
  if balance >= (amount + fee)
    balance -= (amount + fee)
    puts "#{amount}I withdrew the yen. The balance is#{balance}It's a yen"
  else
    puts "Insufficient balance"
  end
end

balance = 100000
puts "How much do you want to withdraw? (It costs 110 yen)"
money = gets.to_i
withdraw(balance, money)

If you follow the way of thinking in order, ① puts "How much do you want to withdraw? (It costs 110 yen)" ② With money = gets.to_i, enter the withdrawal amount with a command and substitute it for money ③ Withdraw argument is defined and jumps to def end (4) Create a conditional expression if else because the output content differs depending on whether the balance is insufficient. ⑤ By setting the conditional expression to balance> = (amount + fee), it is possible to check whether the withdrawal amount is small compared to the balance. expressed ⑥ By writing balance = balance-(amount + fee), the balance amount is expressed and assigned to balance. ⑦ Write balance-= (amount + fee) to keep the code clean. ⑧ If the balance is insufficient, puts "Insufficient balance" is displayed after else.

I wrote the code as below, but this looks a little dirty. For the time being, the same content is output.


  if balance <  amount - 110
    puts "Insufficient balance"
  else

    puts "#{amount}I withdrew the yen. The balance is#{balance - amount - 110}It's a yen"
  end

Recommended Posts

Ruby deposit system, algorithm problem
Ruby problem ⑦
ruby search problem
[Ruby] FizzBuzz problem
[Ruby] FizzBuzz problem
[Ruby] Ruby API problem
ruby API problem
Ruby algorithm (inject, method definition)
[Ruby] problem with if statement
Calendar creation problem (fun Ruby practice problem)
Introduction to Ruby processing system self-made
[Ruby] Search problem using index method
This problem is soberly difficult ... (Ruby)