上級 › coerce未実装のクラスと数値を演算すると TypeError になる › パターン5
coerce未実装のクラスと数値を演算すると TypeError になる
自作クラスのインスタンスを 数値 + 自作オブジェクト の順で演算すると、Integer側の+が呼ばれます。
1 class Score 2 attr_reader :points 3 def initialize(points) 4 @points = points 5 end 6 def +(other) 7 Score.new(points + other.points) 8 end 9 end 10 11 total = ____________________________ ^ 12 puts total.points
main.rb:11:in `+': Score can't be coerced into Integer (TypeError)
from main.rb:11:in `<main>'
空欄を埋めて実行を通す
自作クラスを数値と組み合わせる演算は、どちらを左に置くかで呼ばれるメソッドが変わることを意識する必要があります。
次の問題