上級 › coerce未実装のクラスと数値を演算すると TypeError になる › パターン3
coerce未実装のクラスと数値を演算すると TypeError になる
自作クラスのインスタンスを 数値 + 自作オブジェクト の順で演算すると、Integer側の+が呼ばれます。
1 class Length 2 attr_reader :cm 3 def initialize(cm) 4 @cm = cm 5 end 6 def +(other) 7 Length.new(cm + other.cm) 8 end 9 end 10 11 total = ______________________________ ^ 12 puts total.cm
main.rb:11:in `+': Length can't be coerced into Integer (TypeError)
from main.rb:11:in `<main>'
空欄を埋めて実行を通す
数値を左に置いた式でも自作クラスの計算を成立させたい場合は、coerceメソッドの実装が必要です。
次の問題