Code Fix

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

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

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

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

空欄を埋めて実行を通す

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

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

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

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

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