Code Fix

上級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>'

空欄を埋めて実行を通す

広告
広告スロット(未設定)

coerce未実装のクラスと数値を演算すると TypeError になる

Integerは自作クラスの値をどう数値として扱えばよいか分からないため、そのクラスにcoerceメソッドが定義されていない限りTypeErrorになります。

このエラーの解説と類題をまとめて見る →

広告
広告スロット(未設定)