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