How to check if two instances of a class have the same content?

I have a class with several properties and I have several instances.
How can verify if two instances have the exact same values (even though they are different places in memory)

In other words how can I compare prs1, prs2, and prs3 in the following example and get true?

class Person
    property name : String
    property height : Float64

    def initialize(@name, @height)
    end
end

prs1 = Person.new(name: "Jane", height: 173.1)
prs2 = prs1.dup
prs3 = Person.new(name: "Jane", height: 173.1)

p! prs1
p! prs2
p! prs3
puts prs1 == prs2  # false
puts prs1 == prs3  # false

and BTW Class - Crystal 1.0.0 indicates there is a clone method as well, but when I tried to write clone instead of dup I got: Error: undefined method 'clone' for Person

Add def_equals @name, @height to your class.

See Object - Crystal 1.1.0-dev.

1 Like

Excellent. thank you!

Please also note that the “root” of the inheritance tree is actually Object, not Class. This is why #clone didn’t work, since that method isn’t defined on Object.

1 Like

I remember @asterite explaining what Class actually is. IIRC it’s kinda misnamed in that it’s not actually the base type for a class, but some higher level global thing or something.

2 Likes