Use ||= to initialize variables if they are not already

이 페이지는 아직 한국어로 제공되지 않으며 번역 작업 중입니다. 번역에 관한 질문이나 의견이 있으시면 언제든지 저희에게 연락해 주십시오.

Metadata

ID: ruby-best-practices/initialization-shorthand

Language: Ruby

Severity: Info

Category: Best Practices

Description

The rule “Use ||= to initialize variables if they are not already” is a best practice in Ruby to ensure clean, readable, and efficient code. The ‘||=’ operator is used to assign a value to a variable only if the variable is currently nil or false. This is a more concise and readable way to express conditional assignment, as opposed to using the unless keyword.

This rule is important because it promotes code clarity and efficiency. Using ‘||=’ for conditional assignment reduces the cognitive load on the developer reading the code, as it clearly expresses the intent in a single, straightforward operation. It also avoids unnecessary assignments when the variable is already initialized, potentially improving performance.

To adhere to this rule, use ‘||=’ whenever you want to assign a value to a variable only if it’s not already initialized. For instance, instead of writing name = 'Bozhidar' unless name, write name ||= 'Bozhidar'. This clearly communicates the intent and ensures the assignment only happens when necessary.

Non-Compliant Code Examples

name = 'Bozhidar' unless name

Compliant Code Examples

name ||= 'Bozhidar'
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Analysis