Cette page n'est pas encore disponible en français, sa traduction est en cours. Si vous avez des questions ou des retours sur notre projet de traduction actuel, n'hésitez pas à nous contacter.
Metadata
ID:ruby-best-practices/identity-comparison
Language: Ruby
Severity: Info
Category: Best Practices
Description
In Ruby, the rule “Prefer equal? over == when comparing object_id” is important to remember because of how these two comparison methods function. The equal? method checks if the two compared references point to the exact same object, while the == method checks if the values of the two objects are the same.
This rule is crucial because when you are comparing object_id, you are actually interested in whether the two objects are the same object, not whether their values are equal. Using == can lead to unexpected results if two different objects have the same object_id.
To adhere to this rule and maintain good coding practices, always use equal? when comparing object_id. This ensures that you are accurately checking if the two objects are the same. For instance, instead of writing foo.object_id == bar.object_id, you should write foo.equal?(bar). This way, you are properly checking for object identity, not object equality.
Non-Compliant Code Examples
foo.object_id==bar.object_id
Compliant Code Examples
foo.equal?(bar)
Seamless integrations. Try Datadog Code Analysis
Datadog Code Analysis
Try this rule and analyze your code with Datadog Code Analysis
How to use this rule
1
2
rulesets:- ruby-best-practices # Rules to enforce Ruby best practices.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Analysis scans to your CI pipelines