Rubyで消費税の計算やってみたヘ(^o^)ノ
こんなメソッドを作ってみます
require 'bigdecimal' Order = Struct.new(:sub_total) def total(order, tax) (BigDecimal(order.sub_total) * BigDecimal(tax.to_s)).ceil end order = Order.new(100) total(order, 1.08) # => 108
でも、これじゃ毎回消費税を渡さないといけないよね...
引数taxに初期値を設定してあげましょう
require 'bigdecimal' Order = Struct.new(:sub_total) def total(order, tax = 1.08) (BigDecimal(order.sub_total) * BigDecimal(tax.to_s)).ceil end order = Order.new(100) total(order) # => 108
でも、日本と海外では消費税ちがうよね...
require 'bigdecimal' TAX_RATES = { jp: 1.08, us: 1.09, } Customer = Struct.new(:name, :country) Order = Struct.new(:sub_total, :customer) def total(order, tax = TAX_RATES[order.customer.country]) (BigDecimal(order.sub_total) * BigDecimal(tax.to_s)).ceil end order = Order.new(100, Customer.new('murajun1978', :jp)) total(order) # => 108
:usに変更すれば
order = Order.new(100, Customer.new('murajun1978', :us)) total(order) # => 109
ユーザの国ごとの消費税で計算することができましたね
もちろんtaxを指定しても使えます
order = Order.new(100, Customer.new('murajun1978', :us)) total(order, 1.10) # => 110
Happy Hacking٩( ‘ω’ )و