Last Updated: February 25, 2016
·
950
· janlelis

Ruby Value Struct Example: Point

How to define a Point class using the value_struct gem:

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