Prefer ranges/between over of complex comparisons

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

Metadata

ID: ruby-code-style/ranges-or-between

Language: Ruby

Severity: Notice

Category: Code Style

Description

The rule “Prefer ranges/between over complex comparisons” advises developers to use the range or between? method for comparisons instead of complex conditional statements. This practice increases the readability and clarity of your code. Complex comparisons using logical operators can be difficult to understand and prone to errors.

This rule is important because it promotes cleaner, more efficient, and easier-to-read code. When code is easier to read, it’s easier to maintain, debug, and less likely to contain hidden bugs. Using the range or between? method is a more concise way to check if a value falls within a specific range.

To adhere to this rule, replace complex comparison statements with the range or between? method. For example, instead of writing foo >= 42 && foo <= 99, you can write (42..99).include?(foo) or foo.between?(42, 99). These alternatives are more straightforward and visually cleaner, making your code easier to understand.

Non-Compliant Code Examples

acceptable_foo if foo >= 42 && foo <= 99

Compliant Code Examples

acceptable_foo if (42..99).include?(foo)
acceptable_foo if foo.between?(42, 99)
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