Como definir uma classe Point usando a gema value_struct:
require 'value_struct'
Point = ValueStruct.new_with_mixins(
:x,
:y,
[:dup_with_changes, :to_h, :freeze, :no_clone],
) do
def initialize(x,y)
raise ArgumentError, 'points must be initilized with two numerics' unless x.is_a?(Numeric) && y.is_a?(Numeric)
super(x,y)
end
def abs
( x**2 + y**2 ) ** 0.5
end
def +(o)
dup(x: x + o.x, y: y + o.y)
end
def -(o)
dup(x: x - o.x, y: y - o.y)
end
def +@
self
end
def -@
dup(x: -x, y: -o.y)
end
def to_c
Complex(x,y)
end
def to_s
"(#{x},#{y})"
end
alias inspect to_s
end