== vs equal? vs eql? in Ruby: Key Differences and Usage
== checks if two objects have the same value, equal? checks if they are the exact same object in memory, and eql? is used for hash key comparison, checking both type and value equality.Quick Comparison
Here is a quick table summarizing the main differences between ==, equal?, and eql? in Ruby.
| Method | Purpose | Checks | Common Use Case | Example Result |
|---|---|---|---|---|
== | Value equality | Compares values, can be overridden | General equality checks | true if values are equal |
equal? | Object identity | Checks if both are the same object | Check if two variables point to the same object | true only if same object |
eql? | Hash key equality | Checks value and type equality | Used by Hash to compare keys | true if same type and value |
Key Differences
The == method in Ruby is designed to check if two objects have equivalent values. It is often overridden in classes to provide meaningful value comparison, like comparing two strings or numbers. For example, two different string objects with the same text will return true when compared with ==.
The equal? method is stricter and checks if both variables point to the exact same object in memory. It does not consider the content or value, only object identity. This means even if two objects look the same, equal? returns false unless they are the same instance.
The eql? method is used mainly by Ruby's Hash class to compare keys. It checks both the value and the type of the objects. For example, 1.eql?(1.0) returns false because one is an integer and the other is a float, even though 1 == 1.0 is true. This makes eql? more strict than == but less strict than equal?.
Code Comparison
a = "hello" b = "hello" c = a puts a == b # true, same content puts a.equal?(b) # false, different objects puts a.equal?(c) # true, same object puts a.eql?(b) # true, same content and type puts 1 == 1.0 # true, values are equal puts 1.eql?(1.0) # false, different types puts 1.equal?(1) # true, same object (small integers are singletons)
equal? Equivalent
x = "world" y = x z = "world" puts x.equal?(y) # true, same object puts x.equal?(z) # false, different objects # Using object_id to show identity puts x.object_id == y.object_id # true puts x.object_id == z.object_id # false
When to Use Which
Choose == when you want to check if two objects have the same value, like comparing strings, numbers, or custom objects with meaningful equality.
Use equal? when you need to confirm if two variables reference the exact same object in memory, which is useful for identity checks.
Use eql? primarily when working with hashes or sets where both type and value must match exactly to consider keys equal.
Key Takeaways
== checks if values are equal and can be customized.equal? checks if two variables point to the same object.eql? checks both value and type, used by hashes for key comparison.== for general equality, equal? for identity, and eql? for strict hash key equality.