Code Fix

上級coerce未実装のクラスと数値を演算すると TypeError になる › パターン4

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

自作クラスのインスタンスを 数値 + 自作オブジェクト の順で演算すると、Integer側の+が呼ばれます。

 1  class Volume
 2    attr_reader :ml
 3    def initialize(ml)
 4      @ml = ml
 5    end
 6    def +(other)
 7      Volume.new(ml + other.ml)
 8    end
 9  end
10  
11  total = ______________________________
                           ^
12  puts total.ml
main.rb:11:in `+': Volume can't be coerced into Integer (TypeError) from main.rb:11:in `<main>'

空欄を埋めて実行を通す

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

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

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

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

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