Prefer until over while for negative conditions

このページは日本語には対応しておりません。随時翻訳に取り組んでいます。翻訳に関してご質問やご意見ございましたら、お気軽にご連絡ください。

Metadata

ID: ruby-best-practices/while-with-negatives

Language: Ruby

Severity: Info

Category: Best Practices

Description

The rule “Prefer until over while for negative conditions” suggests that, when writing loops in Ruby, we should use until instead of while for negative conditions. This is because until is more readable and intuitive when dealing with negative conditions. It allows the code to be more easily understood by other developers, which is crucial for maintaining clean and efficient code.

The importance of this rule lies in the readability and maintainability of the code. Using until for negative conditions makes the code more straightforward and self-explanatory. It reduces the cognitive load required to understand the code, making it easier for other developers to maintain and modify the code in the future.

To follow this rule, you need to replace while with until when dealing with negative conditions. For example, instead of writing perform_work while !is_weekend, you should write perform_work until is_weekend. This change improves the readability of the code without affecting its functionality.

Non-Compliant Code Examples

perform_work while !is_weekend

Compliant Code Examples

perform_work until is_weekend
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