[Ruby on Rails (RoR)] Difference between ==, eql?, equal?, === and object_id in Ruby
==, eql?, equal?, === and object_id
Ruby provide few ways to check object value equality.
Equality operators: == and !=
The == operator, also known as equality or double equal, will return true if both objects are equal and false if they are not.
1 | "abc" == "abc" |
eql?
The eql?
method returns true if obj and other refer to the same hash key. This is used by Hash to test members for equality. For objects of class Object, eql? is synonymous with ==. Subclasses normally continue this tradition by aliasing eql? to their overridden ==method, but there are exceptions. Numeric types, for example, perform type conversion across ==, but not across eql?, so:
1 | 1 == 1.0 #=> true |
equal?
Unlike the ==
operator which tests if both operands are equal, the equal?
method checks if the two operands refer to the same object. This is the strictest form of equality in Ruby.
Case equality operator: ===
Many of Ruby’s built-in classes, such as String, Range, and Regexp, provide their own implementations of the === operator, also known as case-equality, triple equals or threequals. Because it’s implemented differently in each class, it will behave differently depending on the type of object it was called on. Generally, it returns true if the object on the right “belongs to” or “is a member of” the object on the left. For instance, it can be used to test if an object is an instance of a class (or one of its subclasses)
1 | String === "zen" # Output: => true |
object_id
Returns an integer identifier for obj.
The same number will be returned on all calls to object_id for a given object, and no two active objects will share an id.
Note: that some objects of builtin classes are reused for optimization. This is the case for immediate values and frozen string literals.
Immediate values are not passed by reference but are passed by value: nil, true, false, Fixnums, Symbols, and some Floats.
1 | Object.new.object_id == Object.new.object_id # => false |
Summary
I’d roughly summarize my approach to these methods like this:
-
If just comparing the content is eqaul or not, use
eql?
-
If compare the same object, use
equal?
orobject_id
See more exapmple:
1 |
|