Ruby Code
class ShoppingCart attr_reader :items def initialize @items=[] end def add_item(name,price,qty=1) raise ArgumentError,"Quantity must be positive" if qty<=0 @items<<{name: name,price: price,quantity: qty} end def subtotal @items.reduce(0){|sum,item| sum+item[:price]*item[:quantity]} end def total(tax_rate=0.08) sub=subtotal tax=sub*tax_rate {subtotal: sub,tax: tax,total: sub+tax} end end module Discountable def apply_discount(percent) multiplier=(100-percent)/100.0 @items.each{|item| item[:price]*=multiplier} end end
Format
Reset
Copy
Settings
Settings
Indentation Style
Spaces
Tabs
Indent Size
1
2
3
4
6
8
Blank Lines
Preserve
Collapse to one
Remove all
Remove trailing whitespace
Add spaces around operators
Formatted Output