Module: Amount::Arithmetic
- Included in:
- Amount
- Defined in:
- lib/amount/arithmetic.rb
Overview
Arithmetic operators for ‘Amount`. Mixed into `Amount` and inherited by any registered subclass.
All operators preserve the receiver’s class via ‘build`, so subclass identity (`GoldAmount`) survives through `+`, `-`, `*`, `/`, `abs`, `-@`.
Instance Method Summary collapse
- #*(scalar) ⇒ Amount
- #+(other) ⇒ Amount
- #-(other) ⇒ Amount
- #-@ ⇒ Amount
- #/(other) ⇒ Amount, BigDecimal
- #abs ⇒ Amount
Instance Method Details
#*(scalar) ⇒ Amount
55 56 57 58 |
# File 'lib/amount/arithmetic.rb', line 55 def *(scalar) ensure_scalar!(scalar) build((BigDecimal(@atomic) * Amount.coerce_decimal(scalar)).to_i) end |
#+(other) ⇒ Amount
35 36 37 38 |
# File 'lib/amount/arithmetic.rb', line 35 def +(other) rhs = coerce_other_to_self_type!(other) build(@atomic + rhs.atomic) end |
#-(other) ⇒ Amount
45 46 47 48 |
# File 'lib/amount/arithmetic.rb', line 45 def -(other) rhs = coerce_other_to_self_type!(other) build(@atomic - rhs.atomic) end |
#/(other) ⇒ Amount, BigDecimal
68 69 70 71 72 73 74 75 76 77 78 79 80 |
# File 'lib/amount/arithmetic.rb', line 68 def /(other) if other.is_a?(Amount) ensure_same_type!(other) raise ZeroDivisionError if other.zero? BigDecimal(@atomic) / BigDecimal(other.atomic) else ensure_scalar!(other) raise ZeroDivisionError if other.zero? build((BigDecimal(@atomic) / Amount.coerce_decimal(other)).to_i) end end |