Skip to content

Instantly share code, notes, and snippets.

@knugie
Created June 24, 2016 10:51
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save knugie/7495882b4cd2f0f6374992e30d2ff000 to your computer and use it in GitHub Desktop.
Save knugie/7495882b4cd2f0f6374992e30d2ff000 to your computer and use it in GitHub Desktop.
POC type checking when calculating with unit-based values
class Meter
attr_reader :value, :unit
def initialize(value, unit = 'm')
@value = value
@unit = unit
end
def self.[](value)
self.new(value)
end
def +(other)
raise TypeError, 'Added incompatiple units, please use "m"(Meter[<Number>])' unless other.is_a? self.class
self.class.new(value + other.value)
end
def *(other)
if other.respond_to?(:unit)
unit = self.unit + other.unit
value = value * other.value
else
value = @value * other
end
self.class.new(value, unit)
end
end
Meter[4] + Meter[9] * 4
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment