Skip to content
Justice Tech School

to_s, inspect and Comparable

Define to_s for printing and include Comparable plus <=> for ordering.

Example
class V
  include Comparable
  attr_reader :n
  def initialize(n) = @n = n
  def <=>(o) = n <=> o.n
  def to_s = "V(#{n})"
end
puts V.new(1) < V.new(2), [V.new(3), V.new(1)].min, V.new(2).between?(V.new(1), V.new(3))

Result

true
V(1)
true

Exercise

Printing hook.

def ; end

Quiz Test

What does Comparable need?

These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.