Skip to content

Instantly share code, notes, and snippets.

@knugie knugie/poc_meter.rb
Created Jun 24, 2016

Embed
What would you like to do?
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
You can’t perform that action at this time.