이 페이지는 아직 영어로 제공되지 않습니다. 번역 작업 중입니다.
현재 번역 프로젝트에 대한 질문이나 피드백이 있으신 경우 언제든지 연락주시기 바랍니다.

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)
PREVIEWING: brett.blue/embedded-collector-release