Skip to content

Instantly share code, notes, and snippets.

@flickgradley
Created August 6, 2023 03:58
Show Gist options
  • Save flickgradley/ba813f747b6cd56338503f85365c0854 to your computer and use it in GitHub Desktop.
Save flickgradley/ba813f747b6cd56338503f85365c0854 to your computer and use it in GitHub Desktop.
#diff method for Ruby Data classes
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