Recap - Coupon Codes
Part of the Object Oriented Programming section of Coddy's Ruby journey. Lesson 16 of 57.
Challenge
MediumComplete the class Coupon. The factory Coupon.parse(code) accepts SAVE followed by a percentage (SAVE10) or OFF followed by an amount (OFF5) and returns nil for any other code. Percentages above the constant MAX_PERCENT (50) are reduced to 50. Every coupon the factory creates is counted in a class instance variable, readable as Coupon.issued; make new private. apply(total) returns the discounted total, never below 0, and to_s returns SAVE10 (10% off) or OFF5 (5.00 off).
The supplied code reads the order total from the first line and one code per following line. It prints SAVE10 (10% off): 90.00 or invalid code HELLO, and finally issued: 2.
Your code goes in coupon.rb. main.rb holds the supplied input/output code and cannot be edited.
Try it yourself
require_relative 'coupon'
# Supplied input/output code: keep it as it is
input = []
while (line = gets)
input << line.chomp
end
total = input[0].to_f
input.drop(1).each do |code|
coupon = Coupon.parse(code)
if coupon
puts format("%s: %.2f", coupon, coupon.apply(total))
else
puts "invalid code #{code}"
end
end
puts "issued: #{Coupon.issued}"
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesInstance VariablesMethods and selfto_s and inspectRecap - Library Card7Polymorphism and Duck Typing
PolymorphismDuck TypingAbstract Methodscase and ClassesRecap - Payment Methods2Accessors and Self
Readers and WritersCustom Settersself in MethodsIdentity and EqualityRecap - Contact List8Special Methods
Equality and hashOperator MethodsIndexing and AppendingCustom CollectionsRecap - Fractions11Project: Library Management
Books and MembersBorrowing Books3Class Methods and Variables
Class MethodsClass Instance VariablesConstantsFactory MethodsRecap - Coupon CodesPractice on your own: Online Ruby compiler