Sha256: 39f5f5d991c72495cf2e510df977ef6817fbcb0aedd41fbe2bee80d66754c37d

Contents?: true

Size: 757 Bytes

Versions: 6

Compression:

Stored size: 757 Bytes

Contents

# frozen_string_literal: true
module Measured::Arithmetic
  def +(other)
    arithmetic_operation(other, :+)
  end

  def -(other)
    arithmetic_operation(other, :-)
  end

  def -@
    self.class.new(-self.value, self.unit)
  end

  def scale(other)
    self.class.new(self.value * other, self.unit)
  end

  def coerce(other)
    if other.is_a?(self.class)
      [other, self]
    else
      raise TypeError, "Cannot coerce #{other.class} to #{self.class}"
    end
  end

  def to_i
    raise TypeError, "#{self.class} cannot be converted to an integer"
  end

  private

  def arithmetic_operation(other, operator)
    other, _ = coerce(other)
    self.class.new(self.value.public_send(operator, other.convert_to(self.unit).value), self.unit)
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
measured-2.8.0 lib/measured/arithmetic.rb
measured-2.7.1 lib/measured/arithmetic.rb
measured-2.7.0 lib/measured/arithmetic.rb
measured-2.6.0 lib/measured/arithmetic.rb
measured-2.5.2 lib/measured/arithmetic.rb
measured-2.5.1 lib/measured/arithmetic.rb