DEV Community

Discussion on: Why I love Ruby: equality

 
marcoservetto profile image
Marco Servetto

ok then... I'm interested in the gritty details of circular equality in ruby.
I also wrote on reddit (reddit.com/r/ruby/comments/syemrs/...) searching for a better answer, and I'm getting some, but I'm still confused.

Thread Thread
 
asterite profile image
Ary Borenszweig

The way it works is:

  • you keep a global table of pair of objects being checked for equality
  • before you compare two objects, you check if they are in this global table. If they are, then the answer is "true" (you don't recurse)
  • otherwise, you put them in the table, then you do the comparison, and finally you remove them from the table

What happens if these objects are compared in other threads at the same time? Well, the global table keeps these pairs per thread!

At least that's how it will work in Crystal (supporting recursive to_s is done with a similar algorithm.)

If that default equality isn't a good default, you can always override == in Ruby and Crystal.

Thread Thread
 
asterite profile image
Ary Borenszweig

You can also take a look at the way we are probably going to do it in Crystal (similar to Ruby, but you don't need to understand C): github.com/crystal-lang/crystal/is...