Created
June 24, 2016 10:51
-
-
Save knugie/7495882b4cd2f0f6374992e30d2ff000 to your computer and use it in GitHub Desktop.
POC type checking when calculating with unit-based values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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