Skip to content

Instantly share code, notes, and snippets.

@hchood
Last active December 28, 2015 08:19
Show Gist options
  • Save hchood/7470923 to your computer and use it in GitHub Desktop.
Save hchood/7470923 to your computer and use it in GitHub Desktop.
Ruby Fundamentals I - CHALLENGE
# Ruby Fundamentals I - CHALLENGE
def check_and_format(amount)
formatted_amount = nil
if amount.match(/\A[0-9]*[.][\d]{2}\z/)
formatted_amount = amount.to_f
else
puts "WARNING: Invalid currency detected! Exiting..."
abort
end
formatted_amount
end
# GET AMOUNTS DUE AND TENDERED FROM USER; CHECKS VALIDITY OF AMOUNTS & CONVERTS TO FLOAT
puts "What is the amount due?"
amount_due = gets.chomp
amount_due = check_and_format(amount_due)
puts "What is the amount tendered?"
amount_tendered = gets.chomp
amount_tendered = check_and_format(amount_tendered)
# CALCULATE CHANGE DUE & PRINT RECEIPT or EXIT
total_change_due = amount_tendered - amount_due
total_change_due_formatted = sprintf("%.2f", total_change_due.abs)
if total_change_due >= 0
current_time = Time.now.strftime("%m/%d/%Y %l:%M %p")
puts "===Thank You!==="
puts "The total change due is $#{total_change_due_formatted}"
puts
puts "#{current_time}"
puts "================"
else
puts "WARNING: Customer still owes $#{total_change_due_formatted}! Exiting..."
abort
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment