-
Notifications
You must be signed in to change notification settings - Fork 35
== vs .equal? vs .eql? and Structural Equality vs Physical Equality
I'm still confused between structural equality and physical inequality. I've read the slides and forums online, but the confusion remains.
Question #1:
How do you wrap your mind around the differences between structural equality and physical equality? Is there a helpful analogy or example you use?
Question #2:
How do you wrap your mind around the differences between == vs .equal? vs .eql? Is there a helpful analogy or example you use?
Answer: Question #1: Structural equality compares the contents of two objects, for example, if two strings have the same sequence of characters. Physical equality compares, essentially, the addresses of the two objects to see if they are literally the same chunk of memory. Remember Java: the .equals() method compares object contents (always used for Strings) and is thus Structural Equality, while == compares the address of the objects, and is thus Physical Equality.
Question #2: ==, .equal?, and .eql? boil down to this: == is structural equality, .equal? is physical equality, and .eql? is really only used for hashing purposes. See https://ruby-doc.org/core-2.1.1/Object.html#method-i-eql-3F for more information. == will be the one to use 99% of the time, and is the one overridden by descendants of Object.