Compare objects for equality


Normally using == between two instances will only return true if they are the exact same objects in the memory. If "only" all the attributes are the same then == will be false.

To be able to compare two objects based on their attributes only we can used the def_equals macro.


examples/classes/compare_objects.cr
class Person
  def_equals @name, @height
  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)
prs4 = prs1
prs5 = Person.new(name: "Jane", height: 173.2)
p! prs1
p! prs2
p! prs3
puts prs1 == prs2 # true
puts prs1 == prs3 # true

puts prs1 == prs4 # true
puts prs1 == prs5 # false