Struct, Comparable and to_s
Struct builds small data classes. Include Comparable and define <=> to get sorting and comparison operators. Define to_s for printing.
Example
Point = Struct.new(:x, :y) do
def to_s = "(#{x}, #{y})"
end
p1 = Point.new(1, 2)
puts p1, p1.x
class Ver
include Comparable
attr_reader :n
def initialize(n) = @n = n
def <=>(o) = n <=> o.n
end
puts Ver.new(1) < Ver.new(2), [Ver.new(3), Ver.new(1)].min.nResult
(1, 2) 1 true 1
Exercise
Mix in comparison.
include Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.