Menu
CoddyTech

回顾:支付方式

本课属于 Coddy Ruby 学习旅程的“面向对象编程”单元。第 36 课,共 57 课。

challenge icon

挑战

困难

使用多态、抽象方法和鸭子类型构建结账流程。PaymentMethod#charge(amount) 是一个模板方法:当 available?(amount) 为 false 时,它会返回 nil;否则,它会使用 label 和抽象方法 fee(amount) 返回 card paid 50.00, fee 1.00。在 PaymentMethod 中,fee(amount) 会引发 NotImplementedError。available? 是一个钩子,返回 true。Card 收取 2% 的手续费;PayPal 收取 0.30 加 3% 的手续费;GiftCard.new(balance) 不收取手续费,仅当余额足以支付金额时才可用,并会扣减余额。Voucher.new(value) 不是 PaymentMethod:它只有自己的 charge(amount),当面值足以支付金额时返回 voucher covered 20.00,否则返回 nil。functions.rb 中的辅助函数 checkout(amount, methods) 会按顺序尝试每个方法的 charge,并返回第一个结果;如果都没有结果,则返回 declined。

第一行输入列出支付方式,例如 gift:30,voucher:20,card。之后的每一行都是一个订单金额;提供的代码会为每个金额打印 checkout 的结果。

你的代码要写在 payment_method.rb、card.rb、pay_pal.rb、gift_card.rb、voucher.rb 和 functions.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

亲手试试

require_relative 'payment_method'
require_relative 'card'
require_relative 'pay_pal'
require_relative 'gift_card'
require_relative 'voucher'
require_relative 'functions'

# 提供的输入和输出代码:保持原样
input = []
while (line = gets)
  input << line.chomp
end
methods = input[0].split(",").map do |entry|
  kind, value = entry.split(":")
  case kind
  when "card" then Card.new
  when "paypal" then PayPal.new
  when "gift" then GiftCard.new(value.to_f)
  else Voucher.new(value.to_f)
  end
end
input.drop(1).each { |line| puts checkout(line.to_f, methods) }

面向对象编程中的所有课

自己练习: Ruby 在线编译器