Code Fix

中級Comparable を include しても <=> が無いと比較演算子は使えない › パターン2

Comparable を include しても <=> が無いと比較演算子は使えない

Comparableモジュールをincludeするだけでは <、>、between? などのメソッドは動きません。

 1  class Weight
 2    include Comparable
 3    attr_reader :grams
 4    def initialize(grams)
 5      @grams = grams
 6    end
 7  
 8  ________________________________________________
                            ^
 9  end
10  
11  puts Weight.new(100) < Weight.new(200)
main.rb:11:in `<': comparison of Weight with Weight failed (ArgumentError) from main.rb:11:in `<main>'

空欄を埋めて実行を通す

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

Comparable を include しても <=> が無いと比較演算子は使えない

これらのメソッドは内部で<=>(UFO演算子)を呼び出す仕組みなので、クラス自身に<=>を定義しておく必要があります。

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

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