Skip to content

Instantly share code, notes, and snippets.

@sjwats
Last active December 28, 2015 10:09
Show Gist options
  • Select an option

  • Save sjwats/7484590 to your computer and use it in GitHub Desktop.

Select an option

Save sjwats/7484590 to your computer and use it in GitHub Desktop.
Ruby Fundamentals II Challenge
#LIGHT = 5
#MEDIUM = 7.5
#BOLD = 9.75
sub_total = 0
sales_list = []
while true
puts "What is the sale price?"
price = gets.chomp
break if price == "done"
price_match = !!price.to_s.match(/\A\d+(\.\d{2})?\z/)
if price_match
sales_list << price.to_f
puts "The sale price is $#{price.to_f}"
sub_total = sales_list.inject(0) {|sum, item_price| sum + item_price}
puts "Subtotal: $#{sub_total}"
else
puts "Invalid amount of currency. Please enter price again with two decimal places/
or type 'done' to complete transaction."
end
end
puts "Here are your item prices:"
sales_list.each{|item| puts "$#{item}"}
puts "The total amount due is $#{sub_total}"
puts "What is the amount tendered?"
while true
amount_tendered = gets.chomp
tendered_match = !!amount_tendered.to_s.match(/\A\d+(\.\d{2})?\z/)
if amount_tendered.to_f >= sub_total
if tendered_match
change = amount_tendered.to_f - sub_total.to_f
puts "===Thank You!==="
puts "The total change due is $#{change}."
time_stamp = Time.now()
time_stamp = time_stamp.strftime('%D %H:%M %p')
puts "#{time_stamp}"
puts"================"
break
else puts "Invalid currency. Please re-enter the amount tendered with two/
decimal places"
end
else
abort("WARNING: Customer still owes $#{(amount_tendered.to_f-sub_total).abs}. Exiting...")
end
end
@HeroicEric

Copy link
Copy Markdown

We can refactor lines 37-38 to read

time_stamp = Time.now.strftime('%D %H:%M %p')

@HeroicEric

Copy link
Copy Markdown

We could refactor the second while loop so that it is more readable without changing very much code by simply shoving some of it into a method like this:

def display_change(amount_tendered, subtotal)
  change = amount_tendered.to_f - sub_total.to_f
  puts "===Thank You!==="
  puts "The total change due is $#{change}."
  time_stamp = Time.now.strftime('%D %H:%M %p')
  puts "#{time_stamp}"
  puts"================"
end

# ... omitted code

while true
  amount_tendered = gets.chomp

  if amount_tendered.to_f >= sub_total
    if is_valid_money?(amount_tendered)
      dispsense_change(amount_tendered, subtotal)
      break
    else
      puts "Invalid currency. Please re-enter the amount tendered with two/
        decimal places"
    end
  else
    abort("WARNING: Customer still owes $#{(amount_tendered.to_f-sub_total).abs}. Exiting...")
  end
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment