Created
August 6, 2023 03:58
-
-
Save flickgradley/ba813f747b6cd56338503f85365c0854 to your computer and use it in GitHub Desktop.
#diff method for Ruby Data classes
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
Measure = Data.define(:amount, :unit) do | |
def diff(other) | |
raise ArgumentError.new("other must be same class") unless other.is_a?(self.class) | |
members.inject({}) do |memo, key| | |
thisVal, otherVal = send(key), other.send(key) | |
memo[key] = [thisVal, otherVal] unless thisVal == otherVal | |
memo | |
end | |
end | |
end | |
m1 = Measure.new(1, "km") | |
m2 = m1.with(unit: "g") | |
m1.diff(m2) # {:unit=>["km", "g"]} | |
m1.diff(m1) # {} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment