上級 › coerce未実装のクラスと数値を演算すると TypeError になる › パターン1
coerce未実装のクラスと数値を演算すると TypeError になる
自作クラスのインスタンスを 数値 + 自作オブジェクト の順で演算すると、Integer側の+が呼ばれます。
1 class Money 2 attr_reader :amount 3 def initialize(amount) 4 @amount = amount 5 end 6 def +(other) 7 Money.new(amount + other.amount) 8 end 9 end 10 11 total = ____________________________ ^ 12 puts total.amount
main.rb:11:in `+': Money can't be coerced into Integer (TypeError)
from main.rb:11:in `<main>'
空欄を埋めて実行を通す
数値を左に置いた演算はInteger側の+が呼ばれます。Moneyにcoerceを実装していない限り、数値がMoneyをどう扱えばよいか分かりません。
次の問題